2.1 if / else Statements
Programs rarely need to do the exact same thing every time they run — they need to make decisions based on data. The if statement checks a condition, something that evaluates to true or false, and runs its block of code only when that condition holds.
The optional else provides a fallback path for when it doesn't, and else if chains let you test several conditions in sequence.
int age = 17;
if (age >= 18) {
cout << "You can vote";
} else {
cout << "Not yet";
}
2.2 switch Statement
When you need to compare one variable against many possible fixed values, a long chain of if / else if becomes hard to read and easy to get wrong. The switch statement handles this cleanly by jumping straight to the matching case via a jump table.
Don't forget break — without it, execution "falls through" and keeps running the code in the next case too, which is one of the most common bugs beginners hit.
int day = 3;
switch (day) {
case 1: cout << "Mon"; break;
case 2: cout << "Tue"; break;
case 3: cout << "Wed"; break;
default: cout << "Unknown";
}
Forgetting break; at the end of a case causes "fall-through" — execution silently continues into the next case's code, even if its condition doesn't match.
2.3 Loops (for, while, do-while)
Loops let you repeat a block of code without writing it out multiple times.
- A
forloop: Is ideal when you know in advance how many times to repeat something, because it bundles initialization, condition, and update into a single line. - A
whileloop: Repeats for as long as a condition stays true, checking the condition before each pass. - A
do-whileloop: Is identical, except it checks the condition after each pass, so the loop body always runs at least once even if the condition starts out false.
// for loop: 0 1 2 3 4
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
// while loop: 5 4 3 2 1
int n = 5;
while (n > 0) {
cout << n << " ";
n--;
}
2.4 break, continue, goto
These three keywords change a loop's normal flow:
break: Immediately exits the loop entirely, skipping any remaining iterations.continue: Skips only the rest of the current iteration and jumps straight to the next one.goto: Jumps execution to a labeled line anywhere in the same function — it exists for legacy reasons but is almost always avoided in modern code because it makes a program's logic difficult to trace (spaghetti code).
for (int i = 0; i < 10; i++) {
if (i == 5) break; // stop the loop entirely
if (i % 2 == 0) continue; // skip even numbers
cout << i << " "; // Output: 1 3
}