Programming and Problem Solving with Java

(やまだぃちぅ) #1
5.2 Looping | 221

in which the statements appear in the code; the logical orderis the order in which
we want the statements to be executed.
The ifstatement is one way of making the logical order differ from the phys-
ical order. Looping control structures are another way. A loopexecutes the same
statement (simple or compound) over and over, as long as a condition or set of
conditions is satisfied.
In this chapter, we discuss different kinds of loops and consider how they
are constructed using thewhilestatement. We also discussnested loops(loops that
contain other loops).


The while Statement


The whilestatement, like the ifstatement, tests a condition. Here is the syntax
template for the whilestatement:


Here is an example of one:


count = 1;
while(count <= 25)
count = count + 1;


The whilestatement is a looping control structure. The statement to be executed each
time through the loop is called the bodyof the loop. In the preceding example, the body of
the loop is a statement that adds 1 to the value of count. This whilestatement says to execute
the body repeatedly as long as countis less than or equal to 25. The whilestatement is com-
pleted (and hence the loop stops) when countis greater than 25. The effect of this loop, then,
is to count through the intvalues from 1 to 25.
Just like the condition in an ifstatement, the condition in a whilestatement must be an
expression of type boolean. The whilestatement says, “If the value of the expression is true,
execute the body and then go back and test the expression again. If the value of the expres-
sion is false, skip the body.” Thus the loop body is executed over and over as long as the ex-
pression remains true when it is tested. When the expression is false, the code skips the body
and execution continues at the statement immediately following the loop. Of course, if the
expression is false initially, the body never executes. Figure 5.4 shows the flow of control of
the whilestatement, where Statement1 is the body of the loop and Statement2 is the state-
ment following the loop.


While-Statement

while ( Expression )
Statement

Loop A control structure that
causes a statement or group of
statements to be executed re-
peatedly
Free download pdf