Do..While Loops

do...while loops are exactly like while loops except the condition is checked at the end of the loop, instead of at the beginning. This means that the code in the loop will always be executed at least once. The general form is shown below.
    do
    {
        /*code that is repeated*/
    }while ( <condition> )

As with a while loop, the condition has the same form as the condition in an if clause and can also include boolean operators. The sequence of operations is as follows:

1.  execute the code within the braces
2.  Check the condition and if it is true, go to step 1 and repeat
3.  otherwise, continue execution of the program past the last brace in the loop
The example of adding the numbers from 1 to 100 is shown using the do..while loop. Which loop you use in your program depends on the particular task you are trying to accomplish.

#include <stdio.h>

int main(int argc, char* argv[])
{
    int i, sum = 0;

    /*must do the initialization before the loop*/
    i = 1;
	
    do 	
    {
        sum = sum + i;
        i ++; /*must include the update within the loop code*/
    } while ( i < 100); /*note that a semi-colon is required*/

    printf("The sum of the numbers from 1 to 100 is: %d\n", sum);

    return 0;
}

next


 home                      table of contents                      about