C++ Do While Loop

The C++ do-while loop is used to iterate a part of the program multiple times. If the number of iteration is not fixed and you must have to execute the loop at least once, then you can use do-while loop.

Flow Chart: -
do-while loop
C++ Do-While loop

C++ do-while Loop

Unlike for and while loops, which test the loop condition at the highest of the loop, the do...while loop checks its condition at rock bottom of the loop.

A do...while loop is analogous to a while loop, except that a do...while loop is bound to execute a minimum of just one occasion .

Syntax: -

do
{
//Code will be executed
}while (condition);

Example: -

#include <iostream>
using namespace std;

int main() {
int i=1;
do
{
cout << i <<"\n";
i++;
}while (i <= 5);
}

When the above code is executed, it generates the following Output −

Output:
1
2
3
4
5

C++ Nested do-While Loop

if you employ do-while loop inside another do-while loop, it's referred to as nested do-while loop. The nested do-while loop is executed fully for every outer do-while loop.



Syntax: -

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

Example: -

#include <iostream>
using namespace std;

int main() {
int i=1;
do
{
int j=1;
do
{
cout << i <<" "<< j <<"\n";
j++;
}while(j <= 2);
i++;
}while(i <= 2);
}

When the above code is executed, it generates the following Output −

Output:
1 1
1 2
2 1
2 2


C++ Infinite do-While Loop

If we use true keyword within the condition a part of do-while loop then it'll become infinite do-while loop.


Syntax: -

do
{
//Code will be executed
}while(true);

Example: -

#include <iostream>
using namespace std;

int main() {
do
{
cout << "Infinite do-While Loop";
}while(true);
}

When the above code is compiled and executed, it produces the following Output −

Output:
Infinite do-While Loop
Infinite do-While Loop
Infinite do-While Loop
Infinite do-While Loop
Infinite do-While Loop
.
.
.