A while loop performs the last two of these, using a similar form to the simple if statement.
while ( condition) statementBefore 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.