C++ Do-While Loop

The C++ The do-while loop works in the same way as the while loop, except that it checks the condition after the code block. It will therefore always run through the code block at least once. Notice that this loop ends with a semicolon..

A do-while loop always executes the body at least once as the condition is checked after loop body.

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

Flowchart:

Cpp Do while loop 1
Example

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

snippet
#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

In C++, if you use do-while loop inside the body of 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.

Example

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

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

Infinitive do-while loop

In C++, do-while loop executes as long as its condition is true exactly as while loop. We can create infinite while loop by passing true as the test condition.

Syntax
snippet
do{  
//code to be executed  
}while(true);
Example
snippet
#include <iostream>
using namespace std;
int main() {
      do{  
              cout<<"Infinitive do-while Loop";  
          } while(true);   
}
Output
Infinitive do-while Loop Infinitive do-while Loop Infinitive do-while Loop Infinitive do-while Loop Infinitive do-while Loop ctrl+c
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +