Ch3.8: do while

The do while Statement

A do while loop is similar to a while loop, except the body runs at least once before the condition is checked.


do {
    body
} while (cond);

The condition is checked after the body executes.

Basic Example

This loop prints numbers from 0 to 4.


::std::uint_least32_t i{};

do {
    println("i=", i);
    ++i;
} while (i != 5);

Difference from while

A while loop may not run at all if the condition is false at the start.


::std::uint_least32_t i{5};

while (i != 5) {   // false immediately
    println("never printed");
}

But do while always runs the body once:


::std::uint_least32_t i{5};

do {
    println("printed once");
} while (i != 5);

Summing Example

This sums numbers in [0, 100).


::std::uint_least32_t i{};
::std::uint_least32_t sum{};

do {
    sum = sum + i;
    ++i;
} while (i != 100);

println("sum of [0,100) = ", sum);

Input Validation Example

A classic use of do while is to repeat until valid input is received.


::std::int_least32_t x{};

do {
    print("Enter a number between 1 and 5: ");
    scan(x);
} while (x < 1 || x > 5);

println("You entered: ", x);

The prompt always appears at least once.

Empty-body do while

An empty-body loop is allowed, though rarely needed.


do {
    ;
} while (false);

Pseudo-graph: do while


          ┌───────────────┐
          │     body       │   (runs once)
          └───────┬───────┘
                  │
                  ▼
          ┌───────────────┐
          │     cond       │─── false ───▶ loop ends
          └───────┬───────┘
                  │ true
                  ▼
                  └─────────────── back to body
      

Key takeaways