for, while and do-while
Rocket Run repeats things constantly: a countdown before launch, the game loop that runs every frame, a menu that reappears until you choose to quit. C++ gives you three loops, and each one matches a different question about when to stop.
The rule
for counts, while waits, do-while acts once before asking.
for: when you know how many steps.
for (int i = 3; i >= 1; --i) {
std::cout << i << "...\n";
}
std::cout << "Launch!\n";The header has three parts: set up (int i = 3), test before every pass (i >= 1), and update after every pass (--i).
Range-based for: visit every element of a collection.
std::vector<int> scores{120, 450, 300};
for (int s : scores) { total += s; }while: repeat as long as a condition holds, tested before each pass. It may run zero times.
while (health > 0) { updateFrame(); }do-while: run the body, then test. It always runs at least once.
do {
choice = showMenu();
} while (choice != 0);Inside any loop, break leaves the loop immediately and continue skips the rest of this pass and goes on to the next test.
The shortcut
For a counting loop for (int i = a; i < b; i += step), list the values of i instead of guessing. With a step of 1 and <, there are exactly b - a passes; with <= there is one more.
Start
iis 2. Is 2 < 10? Yes: pass 1.
The classic trap is off-by-one: i <= 5 when you meant i < 5 gives one pass too many, and reading one past the end of an array is undefined behaviour.
Drills
Answer fast — trust the rule.
How many times does for (int i = 0; i < 5; ++i) run its body?
How many times does for (int i = 1; i <= 5; ++i) run?
After int n = 0; do { ++n; } while (n > 5);, what is n?
What does continue do inside a loop?
With scores holding 10, 20 and 30, what is total after for (int s : scores) { if (s == 20) continue; total += s; }, starting from 0?
Remember
- for counts, while waits, do-while acts once before asking.
- Shortcut: list the values of the loop variable instead of guessing.
- Trap:
<=versus<gives an off-by-one.
