Java Reference
In-Depth Information
5.1 The while Loop
The for loops we have been writing since Chapter 2 are fairly simple loops that exe-
cute a predictable number of times. Recall that we call them definite loops because we
know before the loops begin executing exactly how many times they will execute. Now
we want to turn our attention to indefinite loops, which execute an unknown number of
times. Indefinite loops come up often in interactive programs and file processing. For
example, you don't know in advance how many times a user might want to play a
game, and you won't know before you look at a file exactly how much data it stores.
The while loop is the first indefinite loop we will study. It has the following syntax:
while (<test>) {
<statement>;
<statement>;
...
<statement>;
}
The diagram in Figure 5.1 indicates the flow of control for the while loop. The
loop performs its test and, if the test evaluates to true , executes the controlled state-
ments. It repeatedly tests and executes if the test evaluates to true . Only when the
test evaluates to false does the loop terminate.
As Figure 5.1 indicates, the while loop performs its test at the top of the loop,
before the body of the loop is executed. A while loop will not execute its controlled
statements if its test evaluates to false the first time it is evaluated.
Here is an example of a while loop:
int number = 1;
while (number <= 200) {
number *= 2;
}
No
Yes
Is the test true?
Execute the
controlled statement(s)
Execute the statement
after the while loop
Figure 5.1
Flow of while loop
 
Search WWH ::




Custom Search