C++ do…while loop



In the our previous two chapters we have seen for loop and while loop.

C++ do…while loop :

  1. Unlike for and while loops, do..while loop does not test the condition before going in the loop.
  2. do..while statement allow execution of the loop body once and after the execution of loop body one time, condition will be checked before allowing the execution of loop body for second time.
  3. do..while loop is exit controlled loop, i.e condition will be checked after the execution of the body i.e at the time of exit.
  4. do…while loop is guaranteed to execute at least one time

Syntax of do..while loop :

do
{
  statement(s);
}while( condition );

Example of do..while loop :

#include <iostream>
using namespace std;
 
int main ()
{
   // Local variable declaration:
   int i = 0;

   // do loop execution
   do
   {
       cout << "value of i : " << i << endl;
       i++;
   }while( i < 10 );
   
   return 0;
}

Output :

value of i : 0
value of i : 1
value of i : 2
value of i : 3
value of i : 4
value of i : 5
value of i : 6
value of i : 7
value of i : 8
value of i : 9

Flowchart of do..while loop :

cpp-do-while-loop

Difference between do..while and while loop :

do-while while
It is exit controlled loop It is entry controlled loop
The loop executes the statement at least once loop executes the statement only after testing condition
The condition is tested before execution. The loop terminates if the condition becomes false.

Infinite while loop :

Sometimes we need some special kind of loop which should execute the loop body for infinite times. Loop whose body keeps executing infinite number of times is called as infinite loop.

while(1)
   cout << "Hello"; 

In the above example, the condition part is replaced with the integer 1. i.e condition will be always non-zero number so loop continues its execution for infinite time until stack overflow occurres.