C++ Do While Loop

The do while loop in C++ is used to execute a block of code repeatedly as long as a specified condition is true. Unlike the while loop, the do while loop checks the condition after executing the loop body.

This means the loop body will always execute at least once, even if the condition is false.

Syntax

do {
    // code to be executed
} while(condition);

How the Do While Loop Works

  • The code inside the do block runs first.
  • After executing the code, the condition is checked.
  • If the condition is true, the loop runs again.
  • If the condition is false, the loop stops.

Example Program

#include <iostream>
using namespace std;

int main() {

    int i = 1;

    do {
        cout << "Number: " << i << endl;
        i++;
    } while(i <= 5);

    return 0;
}

Output

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Example: Executing Once Even if Condition is False

#include <iostream>
using namespace std;

int main() {

    int number = 10;

    do {
        cout << "This will run at least once.";
    } while(number < 5);

    return 0;
}

Important Notes

  • The loop body executes at least once.
  • The condition is checked after the loop body executes.
  • Always update the loop variable inside the loop to avoid an infinite loop.

Next Topic

Next, learn about the C++ Break Statement.