Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Control Flow and Statements  ›  Capstone Project

for, while and do-while

for / while / do while loops 12 minA 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.

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.

for (int i = 2; i < 10; i += 3)Step 1 of 4
  1. Start

    i is 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.

quick drill

How many times does for (int i = 0; i < 5; ++i) run its body?

quick drill

How many times does for (int i = 1; i <= 5; ++i) run?

quick drill

After int n = 0; do { ++n; } while (n > 5);, what is n?

quick drill

What does continue do inside a loop?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainChoosing the loop

Rocket Run needs three loops: a launch countdown from 3 to 1, a game loop that runs while the player has health, and a menu that must be shown at least once and repeats until the player picks 0. Explain which loop fits each and why.