The C do-while Loop

There are situations where we want a loop to iterate at least once. This is especially common where a loop performs input and terminates on some sort of sentinel value, a special value used to mark the end of input. Using a while or for loop, this requires setting values before the loop begins to ensure that the condition is true. This is known as priming the loop. The term comes from the old practice of manually spraying some fuel into the carburetor of a cold engine in order to help it start.

age = 0;    // Prime the loop
while ( age != -1 )
{
    printf("Enter an age.  Enter -1 when done: ");
    scanf("%d\n", &age);
    ...
}
        

C offers another type of loop that checks the condition after the body is executed, so that priming the loop is unnecessary.

do
{
    printf("Enter an age.  Enter -1 when done: ");
    scanf("%d\n", &age);
    ...
}   while ( age != -1 );    
        
Practice

Note

Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. Rewrite the square roots program from the previous section using a C do-while loop.