C++:C++ While and Do-While Loops with Examples
C++•Loops

C++ While and Do-While Loops with Examples

Use while loops when the iteration count depends on dynamic runtime conditions.

Syntax

while (condition) {} do {} while (condition);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
whileLoopTests condition before running loop body.
do-whileLoopExecutes body at least once before testing condition.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>

int main() {
    int countdown = 3;
    std::cout << "--- While Loop Countdown ---\n";
    while (countdown > 0) {
        std::cout << "T-minus " << countdown << "...\n";
        --countdown;
    }
    std::cout << "Liftoff! 🚀\n\n";

    // do-while executes once even if initial condition is false
    int runOnce = 0;
    do {
        std::cout << "do-while body executed (runOnce = " << runOnce << ")\n";
        ++runOnce;
    } while (runOnce < 1);

    return 0;
}
Expected Output:
--- While Loop Countdown ---
T-minus 3...
T-minus 2...
T-minus 1...
Liftoff! 🚀

do-while body executed (runOnce = 0)

How It Works: Step-by-Step

  • Lines 6-9: Decrements counter and terminates when countdown reaches 0.
  • Lines 14-17: do-while executes block once before evaluating condition.

Key Concepts

  • The while loop re-checks condition at the start of every cycle.
  • do-while is ideal for input validation prompts that must run at least once.
  • Ensure loop condition variables are properly updated inside the body.

Common Mistake: Placing a semicolon immediately after while(condition);

A semicolon creates an empty loop body, creating an immediate infinite loop.

❌ Incorrect
while (x > 0); { --x; } // Infinite loop: body is empty statement!
✅ Correct
while (x > 0) { --x; }

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler