Repeating work with loops
A loop repeats a body while its continuation condition permits another iteration.
Learning objectives
- Explain the initialization, condition, body, and iteration expression of a
forloop. - Choose
whilewhen repetition depends on a changing condition. - Explain why a
do-whilebody executes at least once. - Identify a loop that cannot make progress toward termination.
Prerequisites: variables, comparisons, if statements, and tracing statements one at a time. Review Conditions first.
Counted repetition with for
A for loop is useful when the iteration pattern has a clear starting state, continuation condition, and update. The initialization runs once; the condition is checked before each body execution; the iteration expression runs after the body (including after a continue).
#include <iostream>
int main() {
int total{0};
for (int number{1}; number <= 4; ++number) {
total += number;
}
std::cout << total << '\n';
}| Iteration | number | total after body |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
Condition-controlled repetition with while
A while loop checks its condition before entering the body. It is useful when the number of repetitions is not known in advance, such as reading until a sentinel value or retrying while input is invalid.
#include <iostream>
int main() {
int remaining{3};
while (remaining > 0) {
std::cout << remaining << ' ';
--remaining;
}
std::cout << "Go!\n";
}At-least-once repetition with do while
A do-while loop checks its condition after the body, so the body runs at least once—even if the condition is initially false. The semicolon after the condition is required.
int attempts{0};
do {
++attempts;
} while (attempts < 0);
// attempts is 1, not 0
Termination and common mistakes
- Make sure some state used by the condition changes so the condition can eventually become false.
- Check
<versus<=; they often differ by one iteration. - Do not update an unrelated variable while leaving the loop condition unchanged.
- A loop with an empty condition in a
forstatement has no condition test and needs another deliberate exit.
Practice
- How many times does
for (int i = 2; i < 6; ++i)run? - What does the
whileexample print ifremainingstarts at zero? - Why does the
do-whileexample setattemptsto 1? - Identify the bug:
int i=0; while (i<3) { std::cout << i; }.
Worked answers
Show reasoned answers
- Four times:
iis 2, 3, 4, and 5. - It skips the body and prints only
Go!. - The condition is checked after the body, and the body increments
attemptsonce before the test. iis never changed, so the condition remains true and the loop does not terminate normally.
Summary
Use for for a clear counted pattern, while for a condition checked before each iteration, and do-while when the body must run at least once. Always identify the state that makes the loop stop.