MASIGNASUKAv102
6510051498749449419

C++ Do-While Loop - Learn With AVRK

Add Comments
Sunday, August 29, 2021

Do-While Loop in C++ Language

Do-While loop is used to repeat a part of the program multiple times. If the number of repetitions are not fixed and you have to execute the loop at least once, Then it is suggested to use a do-while loop instead of while loop.

The do-while loop is executed at least once because the condition is checked at the end of the loop body.

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


Flowchart -

Loading...

Do-while Loop Example -

Let's look at an example using a do-while loop to print a table of 1.
#include<iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
}


Output -

1
2
3
4
5
6
7
8
9
10


Nested do-while Loop

If you use a do-while loop inside another do-while loop, it is known as a nested do-while loop. For each outer do-while loop the inner do-while loop executes completely.

Let's look at an example using nested do-while loops -
#include<iostream>
using namespace std;
int main() {
int i = 1;
do{
int j = 1;
do{
cout<<i<<j<<" ";
j++;
} while (j <= 3) ;
cout<<endl;
i++;
} while (i <= 3) ;
cout<<endl;
}


Output -

11 12 13
21 22 23
31 32 33

Infinite do-while Loop

If you passes always true value in a do-while loop, it will be an infinite do-while loop.
do
{
/*code to be executed */
}
while(true);

Infinite do-while Loop Example -

Let's look at an example using infinite do-while loops.
#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<<"Infinite do-while Loop";
} while (true) ;
}


Output -

Infinite do-while Loop
Infinite do-while Loop
Infinite do-while Loop
Infinite do-while Loop
Infinite do-while Loop
Ctrl + C

Also check this out : C++ While loop - Learn With AVRK
Learn With AVRK

Learn With AVRK