While loop in c++


While loop is the simplest loop of C++ language.  This loop executes one or more statement while the given condition remains true. It is useful when the number of iterations is not known in advance.

Syntax:

The syntax of while loop is as follows:

While ( condition)
Statement;
Condition: the condition is given as a relational expression. The statement is executed only if the given condition is true. If the condition false, the statement is never executed.
Statement:  statement is the instruction that is executed when the condition is true. If two or more statement are used, there are given braces {}. It is called body of the loop.
The syntax for compound statement is as follows:
While(condition){
              Statement;
Statement;
                 Statement;
}

Working of ‘while loop’


First of all, the condition is evaluated. If it is true, the control enters the body of the loop and executes all statement in the body. After executing the statement, it again moves to the start of the loop and evaluates the condition again. This process continues as long as the condition remains true. When the condition becomes false, the loop is terminated. While loop terminates only when the condition become false. If the condition remains true, the loop never ends. A loop that has no end point is known as an infinite loop.
The flow chart of while loop as:

While loop program in C++
Suppose : we want to display something on screen five times using while loop.
#include<iostream>
#include<conio>
int main ()
{
int a=0;
while(a<=5)
{
cout<<"i LOve rbatec.."<<endl;
a++;

}
getch ();
return 0;
}

Explanation
The above program uses a variable a, to control the iteration of the loop. It is known as counter variable. The variable a is initialized to 1. When the condition is evaluated for the first time, the value of a is less than 5 so the condition is true. The control enter the body of the screen. The second statement increments the value of a by 1 and makes it 2. The control moves back to the condition after executing both statements. This process continues for five times. When the value of a becomes 6, the condtion becomes false and the loop terminates.

If you want to learn "FOR LOOP" Click Here

Post a Comment

Previous Post Next Post