Home >>C++ Tutorial >C++ Do While Loop

C++ Do While Loop

C++ Do While Loop

In order to iterate a part of the program numerous times, the Do-while loop is used in the C++ programming. It is generally recommended to use the do-while loop in C++ when there is a need to execute the loop for one time at least and the number of iterations are not certain. In general, the do-while loop in C++ has to be executed at least once as the process of checking the condition starts after the body.

Here is the syntax for the same:

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

Here is an example of the do-while loop that will help you understand it better:

#include <iostream>  
using namespace std;  
int main()
{
     int num;
     cout<<"Enter your number: ";
    cin>>num;
    int i=1;
    int table=0;
    do
    {
    table=num*i;    
    cout<<table <<"\n";    
    i++;          
    }
	while(i<=10);

    return 0;
}
Output :
Enter Yout number : 10
10
20
30
40
50
60
70
80
90
100

C++ Nested do-while loop

A do-while loop can be used inside another do-while loop and it is called as the Nested Do-While loop in C++ programming. In this loop, the nested do-while loop is completely executed for each of the outer do-while loop.

Here is an example of the nested do-while loop:

#include <iostream>  
using namespace std;  
int main() 
{  
   int i = 1;    
	 do{    
		  int j = 1;          
		  do{    
			cout<<i<<"\n";        
			  j++;    
			} 
			while (j <= 2) ;    
			i++;    
	  } 
	  while (i <= 2) ;     
}  
Output :
1
1
2
2

No Sidebar ads