C Programming

THE WHILE STATEMENT
The while provides a mechanism for repeating C statements whilst a condition is true. Its format is,


        while( condition )
                program statement;


Somewhere within the body of the while loop a statement must alter the value of the condition to allow the loop to finish.


        /* Sample program including while  */
	#include <stdio.h>

        main()   
        {
                int  loop = 0;

                while( loop <= 10 ) {
                        printf("%d\n", loop);
                        ++loop;
                }
        }


	Sample Program Output
	0
	1
	...
	10

The above program uses a while loop to repeat the statements


          printf("%d\n", loop);
          ++loop;

whilst the value of the variable loop is less than or equal to 10.

Note how the variable upon which the while is dependant is initialised prior to the while statement (in this case the previous line), and also that the value of the variable is altered within the loop, so that eventually the conditional test will succeed and the while loop will terminate.

This program is functionally equivalent to the earlier for program which counted to ten.


©Copyright B Brown. 1984-1999. All rights reserved.