While Loop C++

While Loop C++


The "While" Loop

It is a conditional loop statement. It is used to execute a statement or a set of statements as long as the given condition remains true.


The syntax of the "while" loop is:

While (condition)
statement;

where

condition: It consists of a relational expression . If it is true , the statement or the set of                                          statements given in the while loop is executed.
Statement: It represents the body of loop. The compound statements or a set of statements are                                 written in braces {}.

The while loop for more than one statements is  written as:

while (condition)
{
statements;

When "while" loop statement is executed , the computer first evaluates the given condition. If the given condition is true , the statement or a set of statements  in the body of the "while"  is executed. After executing the statements under "while" , the control shifts back to "while" and the condition is again tested. If the given condition becomes false at any stage during execution , the execution of the body of loop is terminated and control shifts to the statement that comes immediately after the body of the loop.

The body of the loop must contain a statement so that the condition on the loop becomes false during execution of the loop. If the condition of the loop never becomes false , the loop never ends. It becomes an infinite loop.

Program:

#include<iostream.h>
main ()
{
int c;
c=1;
while (c<=5)
{
cout << "I Love Pakistan"<<endl;
c=c+1;
}
cout << "Program ends";
}

In this example, the variable 'c' is assigned a value 1 to make the condition true. When the given condition (c=<5) is tested, it will returns TRUE value, so the body of loop will be executed.
In the body of the loop, the statement "c=c+1;" changes the value of variable during program execution. After executing five times, the value of "c" becomes 6 and the loop is terminated and control shifts to the statement "cout << "Program ends". This statement comes after the body of the loop.

The flow chart of "while" loop is given below:

while loop


Creative Commons License
Pakistan How by Tahira Aijaz is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.