Monday, February 1, 2010

While loop in c programming language

While loop is also an entry controlled type loop in c language.  It’s working style is same as the for loop. The difference is that the three expressions (initialization, conditional and reinitialisation) are not kept in a same place like for loop. They are placed in different positions. The sequence of execution followed by a while loop is same as for loop.

The syntax of while loop is:

While (test expression)
{
Body of the loop.
Within the loop body the loop control
variable is to be reinitialized. Initialization
will be done somewhere above the control
statement
}

No semicolon after the while statement. Like for loop the control statement and the body of the loop makes one statement. In the following exercise we will see how a while loop works.

#include < stdio.h >
void main ()
{
int x=9,i=0;
/*x' is the loop control variable and it is initialized here*/
clrscr ();
while (x! =0) /*test expression*/
{
printf ("Enter any integer value ('0' for exit):");
scanf ("%d", &x);
/*Reinitialisation of 'x'*/
i++;
}
printf ("You have entered: %d", i-1);
printf (" values before breaking the loop");
getch ();
}

How many times the loop body will be executed depends on the user, the program does not decide it.

#include < stdio.h >
void main ()
{
char x;
int i=0;
clrscr ();
printf ("Do you want to see my name on screen (y/n)\n");
scanf ("%c", &x);
while (x=='y')
{
printf ("My name is ***********\n");
fflush (stdin);
printf ("Do you want to see my name again on the screen (y/n)\n");
scanf ("%c", &x);
i++;
}
if (i > 1)
{
printf ("So weak memory! took %d times to memorize my name", i);
}
getch ();
}

Any Question ? Put Your comments

4 comments:

  1. fflush() is a function in stdio.h header file and it is used in turbo c++ editor to flush out the string or character value stored in the standard input stream i,e stdin

    ReplyDelete
  2. i=1;
    while(++i);
    {
    printf("%d",i);
    }

    Output=1
    why??

    ReplyDelete
  3. Is it 1 or 0?
    You have used an infinite loop and the loop is of empty body as semicolon is placed after the control statement so the statement 'println("%d",i);' is not within the loop body. Now, 'i' increases and ultimately it reached the maximum int range limit 32767, then it comes to -32768 and again starts increment by 1 until it reaches '0' which means false and the loop body breaks. so the output will be 0.

    ReplyDelete

Subscribe via email

Enter your email address:

Delivered by FeedBurner