Skip to main content

Do-while loop

The do-while loop is very similar to the while loop but with one important difference: whilst the while latter evaluates first and then executes the statements, using a condition specified at the beginning of the loop, the do-while loop evaluates after the first execution and the condition isn't specified until after its body.

This means that the body of a do-while loop is always executed at least once, regardless of whether the condition is met.

While loop flowchart

Fig.1. Flowchart of the do-while loop.

Syntax:

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

Example​

Let's take the previous lesson's example and convert it to a program that uses a do-while loop:

int count = 1; // initialize the counter

do {
cout << count << ' '; // print the counter and add some space
count++; // update the counter
} while (count <= 5);
1 2 3 4 5

Use​

Do-while loops are usually used to check that the input of the user is correct. In particular, the input is prompted to the user repeatedly until it inserts a valid input. For example:

positive-number-input.cpp
#include <iostream>
using namespace std;

int main() {
int n;

do {
cout << "insert a positive number:" << endl;
cin >> n;
} while (n <= 0); // if negative or null, ask again

cout << "you inserted a valid number" << endl;

return 0;
}