Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 171 ยท Control Flow

while and do-while Loops

Learn C++ while and do-while loops - how conditions are checked, input loops that read until end of input, validation loops, infinite loops with break and loop bugs.

Computers are good at doing the same thing many times. A loop runs a block of code repeatedly, and the while loop is the simplest kind: as long as a condition is true, keep going. It's the natural choice when you don't know in advance how many repetitions you need: read input until there's no more, retry until the user types something valid, keep halving a number until it reaches 1.

C++ has two forms. The while loop checks its condition before each pass, so it may run zero times. The do-while loop checks after each pass, so it always runs at least once. In this lesson you'll learn both, the input-loop idioms you'll use in almost every program that reads data, how to write deliberate infinite loops, and the bugs that make loops run forever or one time too many.

The while loop

A while loop looks like an if that repeats:

C++
while (condition) {
    // body: runs again and again while condition is true
}

Each time around, C++ evaluates the condition. If it's true, the body runs and then the condition is checked again. If it's false, the loop ends and the program continues after the closing brace. If the condition is false the very first time, the body never runs at all.

C++ Counting with while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every useful loop needs three ingredients: a variable the condition depends on, a condition that eventually becomes false, and a body that changes the variable to move toward that point. Leave out the change (--countdown) and the loop never ends.

For counting from one number to another, you'll usually prefer a for loop, which puts the start, the condition and the step on one line. while shines when the number of passes depends on the data.

Loops driven by the data

Many classic algorithms are while loops that keep transforming a value until it reaches some state. Here are three. Notice how none of them could easily say up front how many times they'll repeat.

C++ Digit sum, GCD and the Collatz sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Euclid's algorithm is over 2,000 years old and still one of the fastest ways to compute a greatest common divisor. (C++17 provides it ready-made as std::gcd in <numeric>; see Math Functions.)

The do-while loop

A do-while loop puts the condition at the end:

C++
do {
    // body: always runs at least once
} while (condition);   // note the semicolon

The body runs first, then the condition decides whether to go around again. Use it when the first pass must happen no matter what, typically because the condition depends on something the body produces, like a choice the user makes.

C++ A menu with do-while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The menu has to be shown before the user can choose, so a do-while fits perfectly. With a plain while, you'd have to give choice a fake starting value just to get into the loop. The break inside the if leaves the loop early if the input runs out; inside the switch, break only leaves the switch.

Don't forget the semicolon after while (condition) in a do-while. It's required there, and it's the only loop where it is. A semicolon after a normal while (condition) is a bug: it creates an empty loop body.

Input loops

The most common while loop in C++ reads input until there is no more. It relies on a feature of streams: the expression std::cin >> x returns the stream itself, and a stream converts to false once a read fails, either because input ended (EOF) or because the text didn't fit the type.

C++ Reading until the input ends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

>> skips spaces and newlines, so it doesn't matter how the numbers are spread over lines. To process input line by line instead, loop on std::getline, which returns the stream the same way:

C++
std::string line;
int line_number = 0;
while (std::getline(std::cin, line)) {
    ++line_number;
    std::println("{:>3}: {}", line_number, line);
}

Don't write while (!std::cin.eof()) instead. That checks for the end before trying to read, so the last read fails while the body still runs with stale data, and a non-number in the input makes it loop forever. Always put the read itself in the condition. Reading User Input and I/O Streams in Depth explain stream states fully.

Retrying until the input is valid

A validation loop keeps asking until it gets acceptable input. When >> fails because the text isn't a number, the stream enters a failed state and refuses all further reads until you call clear(), and the bad text is still waiting in the input. You must also throw it away with ignore():

C++ Asking again until the input is valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Remove the clear() and ignore() lines and run it again: the first bad input sends the loop spinning, because every later read fails instantly. Our runner stops it after a few seconds, but in a terminal it would print forever. The EOF check matters too: without it, a user who closes the input would also trigger an endless loop.

Infinite loops and break

while (true) is a loop that never ends by itself. That's useful when the natural exit point is in the middle of the body, not at the top or bottom. You leave with break (or return from the function). The validation loop above is one example; a game loop or a server's "accept the next connection" loop are others.

C++ A guessing game with while (true)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The guesses follow a binary search: each one halves the remaining range. You'll learn more ways to leave loops, including breaking out of nested loops, in break, continue and goto. for (;;) is another common spelling of an infinite loop; both compile to the same code.

A loop that does nothing visible must end. C++ lets the compiler assume that every loop without observable side effects (no I/O, no volatile or atomic access) eventually terminates. A loop like while (x != 1) { x = f(x); } that would actually spin forever with no output is undefined behavior, and the optimizer may remove it. C++26 makes the trivial while (true) {} well-defined, but the general rule stays. In practice: infinite loops should always do I/O, wait on something, or break.

Loop bugs to watch for

Forgetting to update the variable. while (i < 10) { std::println("{}", i); } without ++i never ends.

Off-by-one errors. while (i <= n) and while (i < n) differ by exactly one pass. Before running a loop, check it in your head with the smallest cases: what happens when n is 0? When it's 1?

A stray semicolon. while (n > 0); has an empty body, so it either does nothing or spins forever. GCC warns (-Wmisleading-indentation, part of -Wall) when the following block is indented like a body.

Floating-point counters. double x = 0; while (x != 1.0) { x += 0.1; } never ends, because ten additions of 0.1 give 0.9999999999999999, not 1.0. Use <, or count with an integer and compute the double from it (see Floating-Point Numbers).

Unsigned counting down. std::size_t i = n; while (i >= 0) { ...; --i; } never ends: an unsigned value is always >= 0, and 0 - 1 wraps to a huge number (see Integer Types). Test i > 0 and decrement inside, or use a signed type.

C++ Fixing two classic loop bugs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first loop stops after 10 passes even though x isn't exactly 1.0, thanks to the small tolerance. The second visits indexes 3, 2, 1, 0 and stops cleanly, because the test i > 0 happens before the decrement.

Choosing a loop

Situation Loop
Repeat while a condition holds; may run zero times while
Body must run at least once (menus, "try, then check") do-while
Read until the input ends while (std::cin >> x) or while (std::getline(std::cin, line))
Exit in the middle of the body while (true) + break
Count from a start to an end with a fixed step for
Visit every element of a container range-based for

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int n = 0; while (n > 0) { --n; } How many times does the body run?

    A while loop checks its condition before the first pass. n > 0 is false immediately, so the body never runs.
  2. 2. int n = 0; do { --n; } while (n > 0); What is n afterwards?

    A do-while loop runs its body once before checking the condition. n becomes -1, then -1 > 0 is false and the loop stops.
  3. 3. Why is while (std::cin >> x) the right way to read numbers until the input ends?

    The read happens first and its success is the condition. A loop on !cin.eof() checks too early and processes one failed read.
  4. 4. What happens in this loop? std::size_t i = 3; while (i >= 0) { --i; }

    i is unsigned, so i >= 0 is always true. After 0, --i wraps to the maximum value and the loop continues. GCC warns with -Wextra (-Wtype-limits).
  5. 5. In an input-validation loop, why do you call std::cin.clear() and std::cin.ignore(...) after a failed read?

    After a failed >>, the stream refuses further reads until it is cleared, and the offending characters remain in the input. Without both calls the loop fails forever.

Summary

  • while (condition) { ... } checks before every pass and may run zero times; the body must move the condition toward false.
  • do { ... } while (condition); runs at least once; remember the final semicolon.
  • Read until input ends with while (std::cin >> x) or while (std::getline(std::cin, line)), never while (!std::cin.eof()).
  • In validation loops, clear() the stream and ignore() the bad line after a failed read, and handle EOF.
  • while (true) plus break is the clean way to exit in the middle; loops with no observable effects must terminate.
  • Watch for missing updates, off-by-one conditions, stray semicolons, != on doubles and unsigned countdowns.

Next: for Loops and Range-Based for, the compact loops for counting and for visiting every element of a container.