C++ While loop



C++ While loop :

  1. The while loop is used for repetitive execution of the statements based on the given conditions.
  2. If condition fails then control goes outside the while loop. If condition becomes true then while loop body will be executed.
  3. True condition can be any non-zero number and Zero is considered as false condition

Syntax for the while-loop :

while(condition)
{
   statement(s);
}

Flowchart of the while loop :

C++ while loop

Example of the while loop :

#include <iostream>
using namespace std;
 
int main ()
{
   // Local variable declaration
   int num = 5;

   // while loop execution
   while( num < 10 )
   {
       cout << "Number : " << num << endl;
       num++;
   }
   return 0;
}

Output :

Number : 5
Number : 6
Number : 7
Number : 8
Number : 9

Explanation :

In the above program we have declared a variable having initial value equal to 5.

int num = 5;

Now in the while condition, we have variable value less than 9 so the condition becomes true so while body gets executed.

while( num < 10 )

Now in the while loop if the value of num becomes 10 then the condition becomes false, in that case while loop body will not be executed.

Some more example of while loop :

A. Infinite while loop

In the below example, we have infinite while loop -

while( 1 )
   {
       cout << "Number : " << num << endl;
       num++;
   }

Now we know that any character variable can converted to integer using the ASCII representation. so we can also have infinite loop like this -

while( 'A' )
   {
       cout << "Number : " << num << endl;
       num++;
   }