for, while and do-while
A for loop counts through a known range, a while loop repeats as long as a condition holds, and a do-while loop always runs its body once before testing.
Select a loop by when it checks its condition and how it advances.
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.