Search Your Topic

config
Monday, 12 June 2017 01:44

C++ Do-While Loop

Written by
Rate this item
(0 votes)

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

The C++ do-while loop is executed at least once because condition is checked after loop body.

 
  1. do{    
  2. //code to be executed    
  3. }while(condition);  

Flowchart:

Cpp Do while loop 1


C++ do-while Loop Example

Let's see a simple example of C++ do-while loop to print the table of 1.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. int main() {  
  4.      int i = 1;    
  5.           do{    
  6.               cout<<i<<"\n";    
  7.               i++;    
  8.           } while (i <= 10) ;    
  9. }  

Output:

1
2
3
4
5
6
7
8
9
10

C++ Nested do-while Loop

In C++, if you use do-while loop inside another do-while loop, it is known as nested do-while loop. The nested do-while loop is executed fully for each outer do-while loop.

Let's see a simple example of nested do-while loop in C++.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. int main() {  
  4.      int i = 1;    
  5.          do{    
  6.               int j = 1;          
  7.               do{    
  8.                 cout<<i<<"\n";        
  9.                   j++;    
  10.               } while (j <= 3) ;    
  11.               i++;    
  12.           } while (i <= 3) ;     
  13. }  

Output:

1 1
1 2
1 3
2 1
2 2 
2 3
3 1
3 2
3 3

C++ Infinitive do-while Loop

In C++, if you pass true in the do-while loop, it will be infinitive do-while loop.

 
  1. do{    
  2. //code to be executed    
  3. }while(true);  

C++ Infinitive do-while Loop Example

 
  1. #include <iostream>  
  2. using namespace std;  
  3. int main() {  
  4.       do{    
  5.               cout<<"Infinitive do-while Loop";    
  6.           } while(true);     
  7. }  

Output:

Infinitive do-while Loop 
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c
Read 158 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in
More in this category: « C++ While loop C++ Break Statement »

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.