Menu

C++ while Loop: Syntax, do-while, and Pitfalls

The C++ while loop explained - the condition-first while, the run-at-least-once do-while, looping until a sentinel, break and continue, and how to avoid infinite loops.

This page includes runnable editors - edit, run, and see output instantly.

When You Don't Have a Counter

The for loop is built around a counter you set up front. But plenty of loops have no clean count: keep reading numbers until input runs out, keep asking for a password until it is correct, keep halving a value until it reaches 1. For those, the while loop is the natural fit - it just repeats while a condition stays true.

A while loop checks its condition before every pass, including the very first. If the condition is false to begin with, the body never runs at all.

The condition count > 0 is checked first; if it's true the body runs, then we loop back and check again. The line count-- is what eventually makes the condition false - drop it and the loop runs forever.

The Anatomy of a while Loop

Compare it to the three-part for loop you already know. A while loop pulls those three jobs apart: you do the setup before the loop, the condition goes in the parentheses, and the update lives inside the body.

int i = 0;          // initialization - before the loop
while (i < 5) {     // condition - checked each pass
    cout << i << "\n";
    i++;            // update - you must remember this yourself
}

That last part is the catch. In a for loop the update sits right next to the condition, so it's hard to forget. In a while loop it's just another statement in the body - the single most common bug is leaving it out and hanging the program.

One C++ gotcha that bites beginners: a stray semicolon right after the condition turns the body into an empty statement.

int i = 0;
while (i < 5);   // <-- this semicolon is the entire loop body
{
    cout << i << "\n";
    i++;
}

That loops forever doing nothing, because the ; is the body and i never changes. The block in braces then runs exactly once. The compiler won't stop you - it's perfectly legal code, just not what you meant.

do-while: Run the Body at Least Once

Sometimes you need the body to run once before you can even decide whether to repeat. The do-while loop checks its condition at the bottom, so the body always executes at least one time:

You have to prompt and read at least once before you can know whether the input is valid, which is exactly what do-while gives you. Note the semicolon after while (...) - in C++ it is required for do-while, and forgetting it is a frequent compile error.

The difference from a plain while shows up clearly when the condition starts out false:

Only do-while body prints. The while loop skips its body entirely because x < 5 was false before the first check.

Looping Until cin Fails

A classic while use is reading until input stops - there's no counter, you just keep going until the stream tells you to quit. In C++, cin >> value evaluates to the stream itself, which is truthy while reading succeeds and falsy once it hits end-of-input or a type mismatch. That makes it a clean loop condition:

The condition does double duty: it reads and tests in one step. Contrast this with a sentinel value - say, stopping on 0. There you must read once before the loop and again at the bottom of each pass so the condition always tests fresh input:

If you forget the second read inside the body, value never changes and you've got an infinite loop. The while (cin >> value) form sidesteps that by folding the read into the condition.

break and continue in while Loops

break and continue work the same here as in a for loop. break leaves the loop immediately; continue jumps straight back to the condition check, skipping the rest of the current pass:

This prints 1 3 5 7 9. The while (true) deliberately never stops on its own - the break is the only exit. Be careful with continue in a while loop: because the update is part of the body, jumping back to the top with continue before you've advanced your counter is a quiet way to hang the loop. In the example above n++ runs first, so it's safe.

Watch Out for Infinite Loops

The condition has to eventually become false, and that depends entirely on something inside the body changing. The two usual culprits are forgetting the update and updating in a way that skips past the exit value:

int i = 0;
while (i < 5) {
    cout << i << "\n";   // i never changes -> runs forever
}
int i = 0;
while (i != 10) {
    i += 3;   // 0, 3, 6, 9, 12... steps right past 10 -> runs forever
}

The first hangs because i is never updated. The second hangs because the counter steps over the exact value the condition looks for - prefer < or <= over != when the step might not land exactly. A while (true) is fine if it has a guaranteed break; an accidental one is just a bug. And remember the empty-body while (...); trap from earlier - a misplaced semicolon produces an infinite loop that looks correct at a glance.

Next: The Range-Based for Loop

A while loop is the right tool when you're looping until a condition changes and there's no clean count. But when you simply want to visit every element of a container - a vector, an array, a string - with no index and no condition to manage, modern C++ has something cleaner: the range-based for loop (for (auto x : container)). That's the next page.

Frequently Asked Questions

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

A while loop checks its condition before the first pass, so the body can run zero times. A do-while loop runs the body once first, then checks the condition at the bottom - so it always runs at least once. Use do-while when the work must happen before you can decide whether to repeat, like prompting for input and then validating it. Note that do-while needs a semicolon after the closing while (...).

When should I use a while loop instead of a for loop in C++?

Use a while loop when you do not have a clean counter and just want to repeat until some condition changes - reading input until cin fails, polling until a value is ready, or processing a queue until it is empty. Reach for a for loop when you know the iteration count or have an obvious index to count.

How do you stop an infinite while loop in C++?

Make sure something inside the body eventually makes the condition false (decrement a counter, advance a pointer, set a flag). For an intentional while (true) loop, put a break inside guarded by an if. If a loop hangs, the usual cause is forgetting to update the variable the condition depends on.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED