Explain while statement with syntax and example
The while statement is similar to those used in other languages although more can be done with the expression statement -- a standard feature of C.
The while has the form:
while (expression)
statement
For example:
int x=3;
main()
{ while (x>0)
{ printf("x=%d n",x);
x-;
}
}
...outputs:
x=3
x=2
x=1
...to the screen.
Because the while loop can accept expressions, not just conditions, the following are all legal:-
while (x-);
while (x=x+1);
while (x+=5);
Using this type of expression, only when the result of x-, x=x+1, or x+=5, evaluates to 0 will the while condition fail and the loop be exited.
We can go further still and perform complete operations within the while expression:
while (i++ < 10);
while ( (ch = getchar()) != `q')
putchar(ch);
The first example counts i up to 10.
The second example uses C standard library functions. getchar() - reads a character from the keyboard - and putchar() - writes a given char to screen. The while loop will proceed to read from the keyboard and echo characters to the screen until a 'q' character is read. NOTE: This type of operation is used a lot in C and not just with character reading!!