The do-while Loop
You may note that in the for and while statements, the expressions are set at the top of the loop. However, in this section, you're going to see another statement used for looping,
do-while, which puts the expressions at the bottom of the loop. In this way, the statements controlled by the do-while statement are executed at least once before the expression is tested. Note that statements in a for or while loop are not executed at all if the condition expression does not hold in the for or while statement.
The general form for the do-while statement is
do {
statement1;
statement2;
.
.
.
} while (expression);
Here expression is the field for the expression that is evaluated in order to determine whether the statements inside the statement block are to be executed one more time. If the expression returns a nonzero value, the do-while loop continues; otherwise, the looping stops.
Note that the do-while statement ends with a semicolon, which is an important distinction from the if and while statements.
The program in Listing 7.6 displays the characters A through G by using a do-while loop to repeat the printing and adding.
TYPE
Listing 7.6. Using a do-while loop.
1: /* 07L06.c: Using a do-while loop */
2: #include <stdio.h>
3:
4: main()
5: {
6: int i;
7:
8: i = 65;
9: do {
10: printf("The numeric value of %c is %d.\n", i, i);
11: i++;
12: } while (i<72);
13: return 0;
14: }
OUTPUT
After running the executable 07L06.exe of Listing 7.6, I have the characters A through G, along with their numeric values, shown on the screen as follows:
C:\app> 07L06
The numeric value of A is 65.
The numeric value of B is 66.
The numeric value of C is 67.
The numeric value of D is 68.
The numeric value of E is 69.
The numeric value of F is 70.
The numeric value of G is 71.
C:\app>
ANALYSIS
The statement in line 8 of Listing 7.6 initializes the integer variable i with 65. The integer variable is declared in line 6.
Lines 9_12 contain the do-while loop. The expression i<72 is at the bottom of the loop in line 12. When the loop first starts, the two statements in lines 10 and 11 are executed before the expression is evaluated. Because the integer variable i contains the initial value of 65, the printf() function in line 10 displays the numeric value as well as the corresponding character A on the screen.
After the integer variable i is increased by 1 in line 11, the program control reaches the bottom of the do-while loop. Then the expression i<72 is evaluated. If the relationship in the expression still holds, the program control jumps up to the top of the do-while loop, and then the process is repeated. When the expression returns 0 after i is increased to 72, the do-while loop is terminated immediately.
- 3 views