While and do while loop in C++

In this tutorial, we will learn how to execute statements repeatedly using ‘while and do while loop in C++’ , there difference and how and where to use them with examples.

There may be a condition in where you  will need to execute a block of statement multiple times. Executing the same block of statement multiple time is called loop.

while loop in c++


Syntax of while loop:

while (test_expression) 
{
    //block of code 
}

If the test_expression returns true only then code inside while loop will execute. Unless the code block returns false the code block keeps on executing.

When the test block returns false, the while loop is terminated.

Flowchart of while loop

Here, in while loop there is chance a statement might not execute at all. In first iteration if the condition returns false, the loop body will be skipped.

Example of while loop

//program to print n numbers starting from 1
# include <iostream>
using namespace std;

int main()
{
   int num;

   cout << "Enter a positive integer: ";
   cin >> num;
   int count=1;
   while (count<= num)
   {
      	cout << count;
	count++;
   }
   return 0;
}

Output

Enter a positive integer: 5
1
2
3
4
5

In above program, the entered number is stored in variable num. 

The count is initialized one to print the number starting from 1. In first iteration, the condition

count < = num i.e 1<=5  return true

Hence, the code block inside while loop gets executed. And the count value is updated to 2 by count++.

Similarly, after count value becomes 6. The test expression becomes 6<=5   which return false. This results in termination of while loop.

do…while loop

The do while is similar to the while loop.  If you notice in while loop, the code block inside while may never get executed if the test expression returns false. That means while loop does entry check. 

do while loop in c++

In case of do while, the block of code inside loop gets executed at least once. i.e do while  does exit check. It check the test expression at exist.

Syntax for do while loop:

do
    {
      //block of code
     }while(test_condition);

Flowchart of do while loop

The code block is executed at least once and only then the test expression is evaluated. 

Example of do while loop

# include <iostream>
using namespace std;

 
int main () {

      int a = 5;

   /* do loop execution */
   do {
      cout << a;
      a = a + 1;
   }while( a <=10 );
   return 0;
}

Output

5
6
7
8
9
10

In above program, without testing the test expression the code block is executed. Only at the exist the test expression is evaluated.