Do/While Loop

Do/While Loop in C++: A loop checks the recipe before touching the pan: "is the soup salty enough? No? Then add salt." If it was already salty, you never pick…

The Analogy: Tasting the Soup

A while loop checks the recipe before touching the pan: "is the soup salty enough? No? Then add salt." If it was already salty, you never pick up the spoon.

A do-while loop tastes first. You always take one spoonful, then decide whether to go round again. The body runs at least once, unconditionally, because the test is at the bottom.

That single difference makes do-while the natural shape for anything that must happen before you can judge it: showing a menu, asking for input, rolling a die, sending a first request before deciding whether to retry.


Syntax or Core Structure

#include <iostream>

int main() {
    // Note the semicolon after the condition -- it is required
    int count{1};
    do {
        std::cout << count << " ";
        ++count;
    } while (count <= 5);
    std::cout << "\n";                 // 1 2 3 4 5

    // The defining difference: the body runs even when the condition is false
    int n{100};
    do {
        std::cout << "This prints once\n";
    } while (n < 10);                   // false, but we already ran

    // Compare with while, which prints nothing
    while (n < 10) {
        std::cout << "This never prints\n";
    }

    // The classic use: ask, then check
    int choice{};
    do {
        std::cout << "Pick 1-3: ";
        std::cin >> choice;
    } while (choice < 1 || choice > 3);

    std::cout << "You picked " << choice << "\n";
    return 0;
}

Three syntax points: the body is always braced in practice, the while sits on the same line as the closing brace by convention, and the trailing semicolon is mandatory — omitting it produces a confusing error about the next statement.


Technical Depth: When the Guarantee Helps and When It Hurts

The one-pass guarantee is the whole point

// while: the setup has to be DUPLICATED before the loop
std::cout << "Pick 1-3: ";
std::cin >> choice;
while (choice < 1 || choice > 3) {
    std::cout << "Pick 1-3: ";        // the same two lines again
    std::cin >> choice;
}

// do-while: written once
do {
    std::cout << "Pick 1-3: ";
    std::cin >> choice;
} while (choice < 1 || choice > 3);

Any time you find yourself copying a block above a while loop just so the condition has something to test, you wanted do-while. Duplicated setup is a maintenance trap: fix a bug in one copy and forget the other.

Where the guarantee is a bug

// DANGEROUS: processes an item even when the container is empty
std::size_t i{0};
do {
    std::cout << items[i];        // if items is empty, this is undefined behaviour
    ++i;
} while (i < items.size());

If there is any chance of zero iterations, do-while is the wrong tool. Iterating a container, reading a file that may be empty, or draining a queue all need the test first. The rule is simple: use do-while only when zero passes would be meaningless.

Scope of the loop variable

do {
    int local{5};
    std::cout << local;
} while (local < 10);        // ERROR: local is out of scope in the condition

The condition sits outside the body's scope, so anything it tests must be declared before the do. This is the one structural difference from while that trips people up, and it is why the validated-input pattern declares choice above the loop.

Reading input safely

#include <limits>

int readMenuChoice() {
    int choice{};
    bool valid{false};

    do {
        std::cout << "Choice [1-4]: ";
        if (std::cin >> choice && choice >= 1 && choice <= 4) {
            valid = true;
        } else {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "Please enter 1, 2, 3 or 4.\n";
        }
    } while (!valid);

    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    return choice;
}

Combining the stream test with the range test in one condition means both kinds of bad input take the same recovery path. The valid flag keeps the loop condition readable — while (!valid) says what it means far better than repeating the whole compound test at the bottom.

The three loops compared

whiledo-whilefor
Test positiontopbottomtop
Minimum passes010
Best forunknown count, may be zeromenus, validation, retriesknown count or a range
Counter scopeoutsideoutsideinside the header
Frequency in real codecommonuncommon but ideal when it fitsmost common

do-while is the rarest of the three, and that is fine. It exists for a specific shape, and when your problem has that shape nothing else reads as cleanly.


Real World Example: An ATM Menu

#include <iostream>
#include <iomanip>
#include <limits>

double readAmount(const char* prompt) {
    double amount{};
    do {
        std::cout << prompt;
        if (!(std::cin >> amount)) {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            amount = -1.0;                       // force another pass
            std::cout << "Numbers only.\n";
        } else if (amount <= 0.0) {
            std::cout << "Amount must be positive.\n";
        }
    } while (amount <= 0.0);
    return amount;
}

int main() {
    double balance{250.00};
    int choice{};

    std::cout << std::fixed << std::setprecision(2);

    do {
        std::cout << "\n--- CashPoint ---\n"
                  << "1. Balance\n2. Deposit\n3. Withdraw\n4. Exit\n"
                  << "Choice: ";

        if (!(std::cin >> choice)) {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            choice = 0;                          // an unmatched value
        }

        switch (choice) {
            case 1:
                std::cout << "Balance: " << balance << "\n";
                break;
            case 2: {
                const double amount = readAmount("Deposit: ");
                balance += amount;
                std::cout << "New balance: " << balance << "\n";
                break;
            }
            case 3: {
                const double amount = readAmount("Withdraw: ");
                if (amount > balance) {
                    std::cout << "Insufficient funds.\n";
                } else {
                    balance -= amount;
                    std::cout << "New balance: " << balance << "\n";
                }
                break;
            }
            case 4:
                std::cout << "Card returned.\n";
                break;
            default:
                std::cout << "Pick 1 to 4.\n";
                break;
        }
    } while (choice != 4);

    return 0;
}

Both loops here are do-while for the same reason: you cannot judge the input until you have shown the prompt and read a reply. The outer loop must display the menu at least once, and the inner readAmount must ask at least once. Setting amount = -1.0 after a failed read is a small trick that funnels stream errors into the same condition as out-of-range values, so there is only one exit test to reason about. choice is declared before the do because the condition needs it.


Common Mistakes

  • Forgetting the trailing semicolon after while (condition). The error message points somewhere unhelpful.
  • Using do-while to iterate a container. An empty container means one pass over nothing — undefined behaviour with [].
  • Declaring the tested variable inside the body. It is out of scope in the condition.
  • Not resetting state on a failed read, so a stream error leaves the value unchanged and the condition passes with stale data.
  • Writing while (condition); on its own line far from the closing brace, so readers miss which loop it belongs to.
  • Using continue and expecting it to skip the test. continue in a do-while jumps to the condition, not past it.
  • Choosing do-while because it looks clever. If while reads more naturally, use while.

Best Practices

  1. Use do-while only when zero passes would be meaningless — menus, validation, retry-at-least-once.
  2. Declare every variable the condition tests before the do.
  3. Keep while (...) on the same line as the closing brace so the loop boundary is obvious.
  4. Combine the stream check and the value check in one condition so all bad input takes one recovery path.
  5. Extract validated input into a function like readAmount and reuse it rather than repeating the pattern.
  6. Use a named flag (while (!valid)) when the real condition is long — it documents the exit reason.

Practice Exercises

  1. Dice until six: Roll a random 1–6 with std::mt19937 in a do-while until you get a six, printing every roll and the total number of rolls.
  2. Password retry: Ask for a password up to three times using do-while, granting access on a match and locking out after the third failure. Make sure the prompt appears exactly once per attempt.
  3. Rewrite both ways: Take the ATM menu above and convert the outer loop to a while. Note exactly what you had to duplicate, then write a one-sentence comment explaining which version you would ship.