Skip to content
Theory · Loops · lesson 1 of 8

for, while and do-while

What you'll learn

What you'll learn:

  • repeat an action with for, while and do-while loops;
  • count how many times a loop runs without an off-by-one error;
  • walk through a list of values with a range-for loop;
  • leave a loop early with break and skip an iteration with continue.
A running track: the start int i = 1, a checkpoint arch i <= 5 before each lap and a mark ++i in the notebook after it

To print the numbers 1 to 5, you can write five lines with std::cout. A thousand numbers would take a thousand lines. Instead, you write a loop, a construct that repeats an action while a condition holds.

Picture a runner at a stadium. The coach says, "Keep running laps until you've done five."

The runner steps up to the start line. Before each lap they pass under a checkpoint arch, which checks how many laps are done. Then the runner runs the lap and puts a mark in a notebook. A loop works the same way:

C++
#include <iostream>

int main() {
    for (int i = 1; i <= 5; ++i) {
        std::cout << i << ' ';  // 1 2 3 4 5
    }
    std::cout << '\n';
}

How a for loop runs

The for header has three parts separated by semicolons. Each one matches a part of the stadium, and they run in this order:

  1. The initialization int i = 1 runs once, before the loop starts. This is the start line.
  2. The condition i <= 5 is checked before every pass. This is the checkpoint arch: if the condition is true, the body runs; if it is false, the loop ends.
  3. The body in curly braces runs. This is the lap itself.
  4. The step ++i runs after the body. This is the mark in the notebook. Then the loop goes back to item 2.

The widget runs the same loop with the condition i <= 3: press "Next step" and watch when each part of the header runs.

LiveThe order of the for partsstep 1 of 11 · frames: 1

The initialization int i = 1 runs once

A frame is where the variables of one call live

One pass through the body is called an iteration. This is where the analogy stops: a real runner knows how far they have run, while the loop remembers only the value of i.

When i becomes 6, the condition is false and the loop ends. The variable i is declared in the header, so it is visible only inside the loop. After the closing curly brace of the loop body, the name i no longer exists.

Counting iterations

A loop runs as many times as there are values its counter i takes. In for (int i = 0; i < 5; ++i), those are the values 0 to 4, that is, five iterations. The < sign keeps i from reaching the bound itself.

Replace < with <=, and i reaches 5 too, which makes six iterations. A loop that runs one time too many or too few has an off-by-one error. Interviewers like to show such loops and ask how many times the body runs.

while and do-while loops

A for loop keeps all three parts in its header. The two other kinds of loop are simpler.

The while loop

A while loop checks its condition before every iteration, like for, but it has no initialization or step. The variable is declared before the loop and changed in the body. You pick it when the number of iterations is not known in advance. This is how you count how many integer divisions by 2 it takes to bring 100 down to 1:

C++
int n = 100;
int steps = 0;
while (n > 1) {
    n = n / 2;
    ++steps;
}
std::cout << steps << '\n';  // 6

The values of n go 100, 50, 25, 12, 6, 3, 1. That is six divisions, and at 1 the condition n > 1 turns false.

The do-while loop

A do-while loop runs its body first and only then checks the condition. So its body runs at least once, even if the condition is false from the start. Compare two loops with the same false condition:

C++
int n = 10;
while (n < 5) {
    std::cout << n << '\n';
    ++n;
}
do {
    std::cout << n << '\n';  // 10
    ++n;
} while (n < 5);

Let's walk through what happens:

  1. while checks 10 < 5 right away. The condition is false, the body never runs, and nothing is printed.
  2. do runs the body: it prints 10 and makes n equal to 11.
  3. Only now is n < 5 checked. The condition is false, and the loop ends.

A do-while loop ends with a semicolon after while (n < 5). Without it, the program does not compile.

Common mistake

An unsigned counter in a countdown loop:

C++
for (unsigned i = 3; i >= 0; --i) {  // ✗
    std::cout << i << '\n';
}

An unsigned value is never negative, so the condition i >= 0 is always true. Subtract one from 0, and you get the largest unsigned value, so the loop prints numbers forever. GCC with the -Wextra flag warns that the comparison is always true, but Clang stays silent even with -Wextra. To count down to zero, declare the counter as int: after 0 it becomes -1, and the condition turns false.

Key points

  • The parts of a for header run in order: the initialization once, then the condition, the body, the step and the condition again.
  • A loop with i = 0 and the condition i < n runs n times; with <=, it runs once more.
  • while checks the condition before the body, and do-while after it, so its body runs at least once.
  • An unsigned counter never drops below zero, so the condition i >= 0 is always true for it.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way