Trusted answers to developer questions

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

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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;
}

RELATED TAGS

do-while
while
loop
control
c++
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?