C++ Control Flow: Conditionals and Loops
Make decisions with if/else and switch, and repeat work with while, do-while, and for loops in C++.
Third post in the basic C++ series. Programs mostly run top to bottom, but real programs need decisions and repetition.
If and else#
int score = 85;
if (score >= 90) {
std::cout << "Grade: A\n";
} else if (score >= 70) {
std::cout << "Grade: B\n";
} else {
std::cout << "Grade: C\n";
}cppThe condition must be a boolean expression. Use && for AND, || for OR, and ! for NOT. Always brace the bodies — it prevents bugs when you add a line later.
Switch#
For many discrete values, switch is clearer than a chain of else if:
switch (day) {
case 1:
std::cout << "Monday\n";
break;
case 2:
std::cout << "Tuesday\n";
break;
default:
std::cout << "Weekend\n";
break;
}cppbreak stops fall-through. Forgetting it is a classic C++ bug.
While and do-while#
int n = 3;
while (n > 0) {
std::cout << n << " ";
--n;
}
// prints: 3 2 1cppwhile checks before running. do-while runs at least once:
int n;
do {
std::cout << "Enter a positive number: ";
std::cin >> n;
} while (n <= 0);cppFor loops#
for bundles initialization, condition, and step:
for (int i = 0; i < 5; ++i) {
std::cout << i << " ";
}
// prints: 0 1 2 3 4cppRange-based for#
Iterating over a container is simplest with a range-based loop:
std::vector<int> v{10, 20, 30};
for (int x : v) {
std::cout << x << " ";
}cppbreak and continue#
breakexits the loop immediately.continueskips the rest of the current iteration and moves to the next.
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) continue; // skip even numbers
if (i > 7) break; // stop at 9
std::cout << i << " ";
}
// prints: 1 3 5 7cppConclusion#
Conditionals choose a path; loops repeat work. Together they turn linear code into real logic. Next in this series: functions.