C++ do...while Loop
Unlike for and while loops, which test the loop condition at the beginning, the do...while loop checks its condition at the end of the loop.
The do...while loop is similar to the while loop, but it ensures that the loop body is executed at least once.
Syntax
The syntax for the do...while loop in C++:
do
{
statement(s);
} while( condition );
Note that the condition expression appears at the end of the loop, so the statement(s) within the loop are executed at least once before the condition is tested.
If the condition is true, the control flow jumps back up to the do, and the statement(s) in the loop are executed again. This process repeats until the given condition becomes false.
Flowchart
Example
Example
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration
int a = 10;
// do loop execution
do
{
cout << "Value of a: " << a << endl;
a = a + 1;
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19