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;
}
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: