Decisions and loops
Making the program choose between paths, and repeating work with for and while — plus the two words that steer a loop from inside.
Choosing a path
An if runs a block when a condition is true. The condition is any expression with a true or false answer, and the familiar comparisons work: == for equal, != for not equal, < and > for order. A single equals sign is assignment, not comparison, and writing one inside an if is a mistake the compiler now usually catches.
else if chains let you test several possibilities in order, and the first one that matches wins — so the order is part of the meaning. A bare else at the end catches everything left over, which is how you avoid a case that silently prints nothing.
Repeating work
A for loop has three parts in its parentheses: where to start, how long to keep going, and what to do after each turn. for (int i = 1; i <= 3; i++) counts from one to three. The i++ is a shorthand for adding one.
A while loop repeats as long as its condition stays true, which is the shape to reach for when you do not know the number of turns in advance. Both kinds run the same block of statements, and blocks are the braces { } — the braces themselves have no newline rules, but the code inside them is indented so a reader can see the shape.
Two words that steer
break leaves the loop immediately and continues after it. continue skips the rest of the current turn and goes to the next one. Both are ordinary statements, and both are easy to overuse: a loop whose exit condition is written in its header is easier to read than one that breaks out of the middle.
switch is the other decision tool, a neat way to compare one value against a list of fixed options. It needs a break at the end of each case, which is a rule C++ inherited from C and one of the reasons the if chain is often the friendlier choice.
A grade, and three loops
#include <iostream>
int main() {
int score = 72;
if (score >= 90) {
std::cout << "Grade: A\n";
} else if (score >= 80) {
std::cout << "Grade: B\n";
} else {
std::cout << "Grade: C or below\n";
}
for (int i = 1; i <= 3; i++) {
std::cout << "Attempt " << i << '\n';
}
int count = 2;
while (count > 0) {
std::cout << "Countdown " << count << '\n';
count--;
}
return 0;
}Grades, attempts and a running total
Run it, then change the score and predict the grade before you press Run again. Add a continue that skips the number 2 in the first loop, and make the countdown start at five.
An infinite loop is the usual first accident. If a run never finishes, look at the condition in the loop header: something inside the block has to move it towards false.
The boundaries are where loops break
A loop is defined by its boundaries: where the counter starts, which value still passes the test, and which value comes next. for (int i = 0; i < 3; i++) runs three times, for 0, 1 and 2. i <= 3 runs four times. Both are valid programs; only one matches the intention, so decide the count before you write the header.
The same care applies to while: the condition is checked before the first turn, so a loop whose condition starts false never runs at all. That is useful when the work is optional and a bug when you expected at least one pass. A do ... while is the form that always runs once, and it is the right tool for that case.
A loop inside a loop multiplies the work. The inner body runs once for every turn of the outer loop, so three outer turns and four inner turns make twelve lines. That is the shape of a table, and it is also why a nested loop over a large list can be much slower than it looks.
The order a for loop runs in
A for header is not a single test. The start runs once; then the condition is checked, the body runs, the step runs, and the condition is checked again. The step happens after the body, never before it, which is why i inside the first turn still holds the starting value.
That order also means the condition is evaluated once per turn, not once for the loop. A condition that changes something — while (i++ < 3) — advances the counter as part of the test, so the body sees a value that has already moved. Keep the test free of changes and the loop stays easy to read.
Three loop mistakes to recognise: if (x = 5) assigns instead of comparing, a missing pair of braces makes only the first statement part of the body, and a loop whose counter never changes runs forever. The compiler warns about some of these, but not all — read the header as three separate decisions.
Try these next
- Print the numbers 1 to 10, then print only the even ones using
continue. - Write a countdown with
while, then rewrite it withforso the output is identical. - Print a 3 by 3 grid of stars with two nested loops.
A small table, an even total, a countdown
Run it and check the table against the row and column numbers. Then change the table to four rows and five columns, and make the countdown start at five.
Check what you learned
One question at a time. A wrong answer explains itself — take another go.
Part 1 of 5
In a chain of if and else if tests, how many blocks can run?
