Monday, October 10, 2011

while loop

It is often the case in programming that we want to do something a fixed number of times. Perhaps we want to calculate gross salaries, or convert temperatures form centigrade to Fahrenheit for 20 different cities. The while loop is ideally suited f or such cases.

Syntax of using while loop:
initialise loop counter
while(valid condition)
{
  statement1;
  statement2;
  statement3;
  statement4;
  increment or decrement loop counter;
}

some basic rule of while loop:
  • The statements within the while loop would keep in getting executed till the condition being tested remains true. When the condition becomes false, the control passes to the first statement that follows the body of the while loop.
  • The condition being tested may use relational or logical operators as shown in the following examples:
    while(x<=20)
    while
    (x>=20 && x<=50)
    while
    (x>=10 || (i>=10 && i<=20)||y==15)
  • Almost always, the while must test a condition that will eventually become false, otherwise the loop would be executed forever,indefinitely.
  • It is not necessary that a loop counter must only be an int. It can even be a float.
  • Example of while loop:
#include<stdio.h>
#include<conio.h>
void main()
{
 int i=1;
 while(i<=5)
 {
  printf("%d\n",i);
  i=i+1;  //i++;
 }
 getch();
}
       Output of above program:
1
2
3
4
5

Nested while loop

One or more loop which require execute again and again then these loop and loops place in separate block is known as nested loop.
Example of nested while loop:

/*demonstration of nested while loop*/

#include<stdio.h>
#include<conio.h>
void main()
{
 int r,c,s;
 clrscr();
 r=1;
 while(r<=5)  /*outer loop*/
 {
  c=1;
  while(c<=2)  /*inner loop*/
  {
   s=r+c;
   printf("r=%d c=%d sum=%d\n",r,c,s);
   c++;
  }
  printf("\n");
  r++;
 }
 getch();
}
         Output of above program:
r=1 c=1 sum=2
r=1 c=2 sum=3
r=2 c=1 sum=3
r=2 c=2 sum=4
r=3 c=1 sum=4
r=3 c=2 sum=5
r=4 c=1 sum=5
r=4 c=2 sum=6
r=5 c=1 sum=6
r=5 c=2 sum=7

No comments:

Post a Comment