While loops

Sometimes we want to perform a statement several times, until some condition is true. The general form of a loop contains a number of statements, broken up into the following phases:

A while loop performs the last two of these, using a similar form to the simple if statement.

      while ( condition) statement
Before the while statement you must set up the initial values which determine the condition's value the first time it is tested, otherwise the loop may never be entered. In the statement you must have the possibility for the condition to be changed, otherwise the loop may repeat indefinitely.
#include <stdio.h>
#include <stdlib.h>

    /*Adds up a sequence of integers and writes the total*/
    
    int main() {
        int Next, Total;
        
            /*Initialisation*/
            
        scanf("%d",&Next);
        Total = 0;
        
            /*Loop*/
            
        while (Next != -1) {
            Total = Total + Next;
            scanf("%d",&Next);
        }    /* end loop statement */
        
        printf("The total is %d\n", Total);
        return EXIT_SUCCESS;
    }

Plain text to compile and run.

Some questions on while loops.


Next - for loops.

Back to index.