22


The while statement

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)

This means simply: For all the time expression is true, execute the following statement(s). Stop the execution and continue with the following program as soon the expression becomes untrue.

For example:

int x=3;

main()

{

}

...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);

This will count i up to 10

while ( (ch = getchar()) != "q")

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!!


drago@scri.fsu.edu
Jan. 1997