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:
For example:
...outputs:
...to the screen.
Because the while loop can accept expressions, not just conditions, the following are all legal:-
Using this type of expression, only when the result of x,
x=x+1, or x
,
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:
The first example counts i up to 10.
The second example uses C standard library functions (See Appendix
)
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!! (See Exercises).
Dave.Marshall@cm.cf.ac.uk