When in a program,a single statement or certain group of statements are to be executed repeatedly depending upon certain condition,the while statement is used.
Syntax :
while(test condition)
{
body of the loop;
}
The statements within while loop would keep on getting executed till the condition being tested remains true. When the condition becomes false,the control passes to the first statements that follows the body of the while loop.
- In place of condition,there can be any other valid expression. So long as the expression evaluates to a non-zero value,the statements within the loop would get executed.
- The condition being tested may use relational or logical operators.
Example:
while(j<=2)
{
}
while(j==2 && i<2)
{
}
- While must test a condition that will eventually becomeĀ false,otherwise the loop would be executed forever,indefinitely.
Example:
main()
{
int j;
while(j<=20)
printf(”%d\n”j);
}
Output
indefinite loop
Correct form:
main()
{
int j;
while(j<=20)
{
printf(”%d\n”j);
j++;
}
}




Recent Comments