< previous page page_468 next page >

Page 468
0468-01.gif
Figure 9-1
Flow of Control:While and Do-While
If n is a positive number, both of these versions are equivalent. But if n is 0 or negative, the two loops give different results. In the While version, the final value of sum is 0 because the loop body is never entered. In the Do-While version, the final value ofsum is 1 because the body executes once and then the loop test is made.
Because the While statement tests the condition before executing the body of the loop, it is called a pretest loop. The Do-While statement does the opposite and thus is known as a posttest loop. Figure 9-1 compares the flow of control in the While and Do-While loops.
After we look at two other new looping constructs, we offer some guidelines for determining when to use each type of loop.
The For Statement
The For statement is designed to simplify the writing of count-controlled loops. The following statement prints out the integers from 1 through n:
for (count = 1; count <= n; count++)
    cout << count << endl;
This For statement means Initialize the loop control variable count to 1. While count is less than or equal to n, execute the output statement and increment count by 1. Stop the loop after count has been incremented to n + 1.
In C++, a For statement is merely a compact notation for a While loop. In fact, the compiler essentially translates a For statement into an equivalent While loop as follows:

 
< previous page page_468 next page >