How does a do-while loop work in C++?

A do-while loop in C++ is similar to the while loop. Just as in a while loop, a do-while loop also has a condition which determines when the loop will break.

While vs. do-while loop

The only difference between a do-while and a while loop is that in the former the condition is evaluated once the code in the loop body has executed and in the latter, the condition is evaluated before the code in the loop body is executed.

svg viewer

Syntax

In a do-while loop, the do keyword is followed by curly braces { } containing the code statements. Then the condition is specified for the while loop.

do {
//code statement(s)
} while(condition);

Note: Do not forget the ; after while towards the end


Example

Let’s have a look at the do-while loop syntax in C++, using an example.

#include <iostream>
using namespace std;
int main() {
int x = 10;
do {
cout << "X = " << x << endl;
x++;
} while(x < 20);
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved