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.
do{ //code to be executed }while(condition);
Let's see a simple example of C++ do-while loop to print the table of 1.
#include <iostream> using namespace std; int main() { int i = 1; do{ cout<<i<<"\n"; i++; } while (i <= 10) ; }
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.
Let's see a simple example of nested do-while loop in C++.
#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) ; }
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.
do{ //code to be executed }while(true);
#include <iostream> using namespace std; int main() { do{ cout<<"Infinitive do-while Loop"; } while(true); }