Ads 468x60px

Wednesday 9 January 2013

While Loop

It is a looping statement, it checks the test expression before going inside the loop so it will not evaluate if the expression given is false initially. It is a top tested loop.

Syntax
while (expression)
{
   statement 1;
   statement 2;
   statement n;
   update expression
}

Example
Write a program to print numbers from 1 to 10.
#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int i=1;
while (i<11)
{
cout<<i<<endl;
i++;
}
getch();
}
Explanation
The value of integer i is initialized with 1. The control checks the expression of while that it is less than 11 or not, and founds it true (1 < 11 = True) and gets inside it and prints the value of i and after that with i++ the value of i incremented by 1 so now the value of i is 2 again it comes to check the expression and found that it is true because 2 is also less than 11 again it comes inside the loop and prints the value of i, this process continues unless and until the expression don't become true. When i reaches 11 then the expression becomes false (11 is not less than 11) and the loops breaks. 
Share if you liked this Post using your favorite sharing service:

Subscribe Updates, Its FREE!

0 comments:

Post a Comment

 
Related Posts Plugin for WordPress, Blogger...