while loop

The execution of this type of loop is similar to for-loop, that is, In the first is the variable initialization, then condition is given if the condition is true then the body of loop is executed then the expression value is update or increment As long as the expression value is not false. as soon as the condition is false the loop gets terminate.

SYNTEX:-

initialization;
while(condition)
 {
   Body of loop;
   Updation;
 }

while-loop

Here is the program,

#include<iostream.h>
#include<conio.h>

 void main()
 {
 clrscr();
 int x;
 
  cout<<"Enter number: ";
 cin>>x;

  int i=0; 
  while(i<x) 
   {
      cout<<x<< " "; // body of loop
      i++;
   }

 getch();
}
OUTPUT:-
3 3 3 3 3

click here to see while-loop execution in this program,

Explanation:-

above program implementation is given in below table

increment in initialization value(i=0) condition check(i<x) body of loop execute
0 0<5 (True) 3
1 1<5 (True) 3
2 2<5 (True) 3
3 3<5 (True) 3
4 4<5 (True) 3
5 5<5 (False) can’t execute

 

Related Exercise


previous-loop and their types, for-loop

next-do-while loop