Translate

Labels

Saturday 5 January 2013

LOOP STATEMENT( WHILE )

The while statement is used to execute the set of statements repeatedly till the condition specified remains true.In while statement, the condition is tested at the entry  level.The number of times the loop gets executed is controlled by a control variable. The following  program prints the first ten natural numbers each in one line.Here, a loop is required to execute the printf() function for 10 times.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
i=1;                          /*Initialization*/
while(i<=10)
{
printf("%d\n",i);        /*processing statement*/
i=i+1;                      /*updating*/
}
}
In the above program, the variable i is used as a control variable that will control the execution of the while loop.The control variable is properly initialized just before the while statement .Since the above program is to print the first 10 natural numbers and the first number to be printed is 1, the control variable is initialized to 1 . The loop has to be executed for 10 times and hence the condition i<=10 is used The body of the while loop is executed if the specified condition is true.The control variable is incremented by 1 every time the loop executes so that the loop will be repeated exactly for 10 times.If the test condition fails, the control is transferred out of the loop.On exit, the program continues with the statement immediately after the body of the loop.If you look into the program once again, the control variable is tested immediately after the initialization of it and it is incremented just before the end of the while loop (just before the closing curly brace).The syntax of the while statement is as follows:
Initialization of the control variable 
while(condition)
{
..........,
..........,           processing statements 
updating the control variable;
}
     The control variable is tested against a condition in the while statement and it should be properly updated within the while loop for proper termination of the loop.If the updating line is missing, the value the control variable will be always 1 and the loop never ends.

If we omit the initialization, condition and the updating statements from the above program, it condition and the updating statement, which printf("%\n",i); that will serve the purpose of this program.

No comments: