Language[lang]

C++ while loop (and do-while): syntax and examples

Section
Language [lang]
Standard
C++17
Compilers
MSVC 19.44, Clang 19.1 (MSVC STL), GCC 16.2, Clang 23.1 (libc++)
Published
Length
7 min read
In this answer6 clauses
  1. 1How does a while loop work in C++?
  2. 2How do you read input until it ends with a while loop?
  3. 3What is a do-while loop in C++?
  4. 4How do break and continue work in a while loop?
  5. 5Why does my while loop never stop?
  6. 6While loop or for loop: which should you use?

Abstract

A C++ while loop, while (condition) { ... }, tests its condition before every pass, so its body may run zero times; a do-while, do { ... } while (condition);, tests after, so its body runs at least once. Put a read in the condition to loop until the input ends, leave early with break, and skip to the next test with continue. Three one-line mistakes make a loop that never stops: a body that never changes what the condition tests, a stray semicolon after while (...), and = where == was meant.

A line runs in from the left through six small diamonds on a baseline. Between each pair it rises in a tall loop that circles back on itself; after the sixth diamond it leaves to the right in blue.
Figure 1 — Round and round, until the condition is false.

A C++ while loop repeats a block of code as long as its condition is true: while (condition) { ... }. The condition is checked before every pass, so the block may run zero times. A do-while loop, do { ... } while (condition);, checks after each pass, so its block always runs at least once.

Counting from 1 to 5, in a whole program:

[Example 1:
#include <iostream>

int main() {
    int i = 1;
    while (i <= 5) {
        std::cout << i << '\n';
        ++i;
    }
}

— end example]

It printed:

[Example 2:
1
2
3
4
5

— end example]

i <= 5 is the condition, and the two lines in braces are the body. std::cout << i << '\n' prints i and ends the line (how to print with std::cout); ++i adds one to i. The loops need no header and have been in C++ since C++98. The samples are C++17 (Since When lists the compiler releases for each standard), built with MSVC 19.44, Clang 19.1 (MSVC STL), GCC 16.2 and Clang 23.1 (libc++), and all four printed the same.

How does a while loop work in C++?

It tests the condition; if the condition is true, it runs the body and tests again, and the first time the condition is false, the program goes on after the loop.

Two stacked flowcharts. In the while loop the arrow meets the condition diamond first: true runs the body box and returns, false leads out. In the do-while loop the body comes first, then the condition: true leads back, false out.
Figure 2 — A while loop checks before each pass; a do-while loop checks after, so its body runs at least once.

Something in the body has to move the condition toward false. In the counting example that is ++i: five passes take i from 1 to 6, the sixth test fails, and the loop ends. A condition that is false at the start skips the body entirely:

[Example 3:
int i = 10;
while (i <= 5) {             // false at the start
    std::cout << i << '\n';  // never runs
    ++i;
}
std::cout << "after the loop, i is " << i << '\n';

— end example]

It printed only after the loop, i is 10.

How do you read input until it ends with a while loop?

Put the read in the condition: while (std::cin >> number) runs the body once for each number read, and stops when the input ends or the next thing in it is not a number. Adding up what the user types:

[Example 4:
int number = 0;
int count = 0;
int sum = 0;
while (std::cin >> number) {  // false when the input ends
    ++count;
    sum += number;
}
std::cout << "read " << count << " numbers, sum " << sum << '\n';

— end example]

Given the input 4 8 15, it printed read 3 numbers, sum 27. The condition is the read itself: true when a number came in, false once a read fails, so the loop needs no separate test for the end. When you type the numbers yourself, end the input with Ctrl+D on a new line (Linux, macOS) or Ctrl+Z then Enter (Windows); a word instead of a number ends the loop too. To read whole lines, spaces included, C++ getline puts std::getline in the same kind of loop.

What is a do-while loop in C++?

A do-while loop runs its body first and tests the condition after, so the body always runs at least once (the do-while loop on cppreference). It ends with a semicolon after the while (...). Use it when the body has to run before there is anything to test, such as asking for a menu choice until the answer is valid:

[Example 5:
int choice = 0;
do {
    std::cout << "Choose 1, 2 or 3:\n";
    std::cin >> choice;
} while (choice < 1 || choice > 3);  // note the semicolon
std::cout << "You chose " << choice << '\n';

— end example]

Given 7, 0 and 2, it asked three times and then printed You chose 2. Even with a condition that is false from the start, as in int i = 10; do { ... } while (i <= 5);, a do-while runs its body once: that sample printed i is 10. This menu trusts its input, though: after a letter, or at the end of the input, the read fails and every read after it fails at once, so it asks forever. Reading with if (!(std::cin >> choice)) return 1; in place of std::cin >> choice; ends the program instead.

How do break and continue work in a while loop?

break leaves the loop at once (the break statement on cppreference), and continue skips the rest of the current pass and goes back to the condition. while (true) with a break inside is the usual way to write “loop until something happens”. Finding the first power of 2 above 1000:

[Example 6:
int power = 1;
while (true) {
    power *= 2;
    if (power > 1000) {
        break;  // leaves the loop at once
    }
}
std::cout << power << '\n';  // the first power of 2 above 1000

— end example]

It printed 1024. The condition true cannot fail, so the break is the only way out. continue is for passes that should do nothing more, here the even numbers (% gives the remainder, so i % 2 == 0 means even):

[Example 7:
std::cout << "odd:";
int i = 0;
while (i < 9) {
    ++i;  // before the continue, or the loop never ends
    if (i % 2 == 0) {
        continue;  // skip the rest of this pass
    }
    std::cout << ' ' << i;
}
std::cout << '\n';

— end example]

It printed odd: 1 3 5 7 9. The ++i comes before the continue on purpose: at the end of the body, the first even i would skip it, stay even, and the loop would never end. In a do-while loop, continue jumps to the condition as well (the continue statement on cppreference).

Why does my while loop never stop?

Because its condition stays true, and three one-line mistakes cause that. The first is a body that never changes what the condition tests: take ++i out of the counting example and i stays 1, so i <= 5 holds forever.

The second is a semicolon after while (...). A loop’s body is the one statement after the parentheses, usually a block in braces, and ; on its own is a statement, an empty one:

[Example 8:
while (i <= 5); {  // the ; is the whole body of the loop

— end example]

The loop repeats the empty statement, i stays 1, and the block below is not reached. Clang warns while loop has empty body (-Wempty-body) and GCC that the while clause does not guard... the block (-Wmisleading-indentation), whether the brace is on that line or the next, but MSVC said nothing at /W4: do not count on a warning.

The third is = where == was meant:

[Example 9:
while (x = 5) {  // meant x == 5: = stores 5, so this is always true

— end example]

x = 5 stores 5 in x, and a condition of 5 counts as true, so the test passes every time, whatever the body does to x. All four compilers warn on this one: MSVC with C4706, assignment used as a condition (at /W4), and GCC and Clang under -Wparentheses. Each suggests extra parentheses, while ((x = 5)), which silence the warning but keep the bug: the fix is ==.

While loop or for loop: which should you use?

Use for when you know how many passes you want, while when you loop until something happens, and do-while when the body must run at least once. The same count both ways:

[Example 10:
int i = 1;
while (i <= 5) {
    std::cout << ' ' << i;
    ++i;
}
// ...
for (int i = 1; i <= 5; ++i) {
    std::cout << ' ' << i;
}

— end example]

Both printed 1 2 3 4 5. The for loop gathers the start, the test and the step into one line; the while loop spreads them over three.

You need Write
A known number of passes a for loop
To loop until something happens a while loop
The body to run at least once a do-while loop
A loop that ends from inside while (true) with break
Every element of a container a range-for loop, for (int n : numbers)

The Language section has the other answers on the core language.

Questions

How do you stop a while loop in C++?

Make its condition false, or leave it with break. The condition is tested before every pass, so the loop ends at the first test that comes out false; break ends it at once, from anywhere in the body except inside a switch or an inner loop, where it ends only that. A return inside the loop ends it too, by leaving the whole function.

Can a while loop run zero times?

Yes. A while loop tests its condition before the first pass, so when the condition is false from the start the body never runs and the program goes on after the loop. A do-while loop cannot run zero times: its body runs once before the first test.

What is the difference between while and do-while in C++?

When the condition is tested. A while loop tests it before each pass, so its body may never run; a do-while loop tests it after each pass, so its body always runs at least once. A do-while also ends with a semicolon after the while (condition).

What is the time complexity of a while loop?

The number of passes times the cost of one pass. A loop that counts from 1 to n with a fixed amount of work in its body is O(n), linear in n. A loop that halves a number on every pass runs about log2(n) times, so it is O(log n).

Does continue skip the condition check?

No. In a while loop, continue skips the rest of the body and goes straight to the condition, which is tested before the next pass. In a do-while loop it jumps to the end of the body, where the condition is tested too, so a loop whose condition has become false still stops.

How do you write an infinite loop in C++?

Write while (true) and leave the loop from inside it with break, or with return to leave the whole function. It is the usual shape of a loop that runs until something happens: the way out is a test in the body, not the condition.

Sources

  1. while loopcppreference.com
  2. do-while loopcppreference.com
  3. break statementcppreference.com
  4. continue statementcppreference.com
  5. [stmt.while] The while statementC++ standard working draft

Read next

  1. assert in C++: how assert and static_assert workLanguage · Miriam Castellanos · written for C++17
  2. C++ try catch: how to throw and catch exceptionsLanguage · Miriam Castellanos · written for C++17
  3. C++ ternary operator (?:): syntax and examplesLanguage · Miriam Castellanos · written for C++17