9.2 Additional Control Statements | 445
do
while ( Expression ) ;
Statement
do Statement
false true
false true
while ( Expression )
while Statement
Statement
Figure 9.3 Flow of Control:whileand do
doSolution
sum = 0;
counter = 1;
do
{
sum = sum + counter;
counter++;
} while(counter <= n);
If nis a positive number, both of these versions are equivalent. If nis 0 or negative, how-
ever, the two loops give different results. In the whileversion, the final value of sumis 0 be-
cause the loop body is never entered. In the doversion, the final value of sumis 1 because the
body executes once and thenthe loop test occurs.
Because the whilestatement tests the condition before executing the body of the loop,
it is called a pretest loop. The dostatement does the opposite and thus is known as a posttest
loop. Figure 9.3 compares the flow of control in the whileand doloops.
When we finish introducing all of the new looping constructs, we will offer some guide-
lines for determining when to use each type of loop.
The for Statement
The forstatement is designed to simplify the writing of count-controlled loops. The follow-
ing statement prints out the integers from 1 through n:
for (count = 1; count <= n; count++)
outFile.println("" + count);
This forstatement says, “Initialize the loop control variable countto 1. While countis less
than or equal to n, execute the output statement and increment countby 1. Stop the loop af-
ter counthas been incremented to n+ 1.”