AlgoMaster Logo

Do-While Loop

Medium Priority14 min readUpdated June 6, 2026
Listen to this chapter
Unlock Audio

The do-while loop is the one loop in C++ that always runs its body at least once before checking the condition. That single property makes it the right tool for a small but real set of problems: prompting a user until they enter something valid, showing a menu that repeats until they pick "exit", and retrying an operation a couple of times before giving up. This lesson covers the syntax, the issue with the trailing semicolon, and the situations where do-while reads more naturally than a regular while.

Syntax and Basic Behavior

A do-while loop has three parts: the keyword do, a body in curly braces, and a while (condition); clause at the bottom. That trailing semicolon is mandatory, and forgetting it is one of the most common mistakes when first learning the construct.

The flow is straightforward: enter the body, run it, then check the condition. If the condition is true, jump back to the top of the body and run it again. If it's false, fall through to whatever comes next.

The key behavior that sets do-while apart from while is the order of those two steps. The body runs first, then the condition is checked. Even if the condition is false from the start, the body still runs once.

stock is 0 from the start, so stock > 0 is false the first time it's checked. But the body still ran once, because the check happens at the end of the iteration, not the beginning. With a regular while loop, that body would never execute.

The Trailing Semicolon

The semicolon after while (condition) is not optional. It's part of the do-while statement's syntax. Leaving it off produces a compiler error that's often confusing because it points at the next line, not at the missing semicolon.

What's wrong with this code?

With g++ -std=c++17, this fails with something like:

The compiler keeps reading past the while (...) looking for the semicolon, sees std::cout instead, and complains. The fix is to add the missing ; after the parenthesis:

This is a different shape from for and while loops, where the body's closing brace } ends the statement and no extra semicolon is needed. The asymmetry is intentional: do-while ends with an expression-statement (while (cond);), so it needs the semicolon the same way int x = 5; does.

While vs Do-While, Side by Side

The difference between while and do-while comes down to one question: should the body run at least once, regardless of the condition? A side-by-side comparison makes the contrast obvious.

Same logic, written two ways:

cartItems starts at 0. The while version checks the condition first, sees that 0 > 0 is false, and skips the body entirely. The do-while version runs the body once before checking, prints Processing item 0, decrements cartItems to -1, and only then checks cartItems > 0, which is false.

This zero-iterations difference is the whole point. Sometimes it's the right answer, sometimes it's a bug. Picking between the two loops is picking which behavior is intended.

The general shape of each:

In the while shape, the first arrow goes into the check. In the do-while shape, it goes into the body. That's the whole story, and it drives every decision about when to use one versus the other.

A summary table for quick reference:

Propertywhiledo-while
Where condition is checkedBefore each iterationAfter each iteration
Minimum body executions01
Trailing semicolon?NoYes, after while (...)
Best forPre-tested loops, "loop while data is available"Input validation, menus, retry-then-test

When to Use Do-While

Most loops in C++ should be for or while loops. Pre-tested loops are the common case: read a file until it's empty, iterate over a vector, count from 1 to 10. All of those check the condition first and might run zero iterations.

The do-while loop fits three patterns where the body should run at least once before deciding whether to continue.

Pattern 1: Input Validation

The most common use of do-while is prompting a user for input, checking if it's valid, and reprompting if it isn't. The first prompt is unconditional, so a do-while reads naturally.

Sample run:

The body always runs once because you have to ask the user before you know whether they typed something valid. After each entry, the condition checks whether the value is out of range. If it is, the loop runs the body again and asks once more.

Writing the same thing with a while loop is awkward. You either have to prompt outside the loop and then again inside (duplicating the prompt), or initialize quantity to a known-bad value (like -1) just to force the first check to fail. Both feel like workarounds for the loop choice.

Pattern 2: Menu Loops

A menu loop shows options to a user, accepts a choice, takes action, and repeats until they pick "exit". You always want to show the menu at least once, so the body needs to run before the exit check.

Sample run:

choice is 0 at the start, which means a while (choice != 4) would have entered the body anyway, but the intent is clearer with do-while. You're saying "show the menu, take a choice, repeat unless they picked exit," which matches the structure exactly.

Pattern 3: Retry-Then-Test

Some operations have a built-in "try first, then decide whether to try again" shape. Connecting to a service, validating a payment, anything that could fail and needs a couple of attempts before giving up. The first attempt is unconditional, so the body should run once before the loop checks whether to repeat.

You don't know whether the first attempt will succeed until you actually try it, so the body must run at least once. The condition combines two checks: keep going while we haven't succeeded yet AND we haven't burned all our attempts. As soon as either is true, the loop ends.

Why It's Used Less Than While and For

do-while shows up rarely in C++ code compared to for and while. There's a reason for that. Most loops are pre-tested by nature: you check a condition first to decide whether you should do anything at all. Iterating over a container, counting from a start to an end, reading until end-of-file, processing while a queue has elements. In every one of those, zero iterations is a valid answer if the data isn't there.

do-while only fits when at least one iteration is required by the problem itself. That's a narrower set of cases. The C++ Core Guidelines and most internal style guides don't ban do-while, but they note that any do-while can be rewritten as a while by either duplicating the body's first action or initializing a flag, and that rewrite is often easier to read for someone new to the code.

That said, when the situation genuinely calls for "do, then check," do-while is the clearest way to write it. Input validation and menu loops are the two places where most experienced C++ programmers reach for it without hesitation.

A small tour of common idioms in real code:

All three share the same shape: do the thing, then check whether to do it again. Whenever you see that shape, do-while is the right tool.

Break and Continue Work the Same Way

Inside a do-while loop, break and continue behave just like they do in for and while. break exits the loop immediately, skipping the bottom check. continue jumps to the bottom check (where the condition is evaluated) without running the rest of the body.

while (true) looks unusual but it's a common pattern: an infinite loop that exits only through break inside the body. The continue skips the rest of the body and goes straight to the bottom of the loop, where the condition is checked. Both keywords work in do-while exactly as they do elsewhere.

A Few Common Mistakes

A few specific failure modes show up often when people first use do-while. Spotting them quickly is worth a paragraph each.

Forgetting the semicolon. Already covered above, but worth repeating: while (cond); ends with a semicolon. The compiler error usually points at the next line.

Putting a semicolon in the wrong place. A different version of the same problem:

That do; is a do followed by an empty statement, followed by while (count < 3);. It compiles. It runs forever if count doesn't change. The fix is to use braces around a real body.

Off-by-one on the exit condition. Because the check is at the bottom, the variable's value at exit may differ from what you'd expect with a while. Walk through a small example by hand if you're not sure.

Assuming `do-while` is faster. It isn't. The body runs once unconditionally, but past that, both loops compile to nearly identical machine code. Pick the loop that reads clearly for the problem, not for imagined performance.

Quiz

Do-While Loop Quiz

10 quizzes