Java Reference
In-Depth Information
Designing while Loops
As shown in Example 5-1, the body of a while loop executes only when the expression
in the while statement evaluates to true . Typically, the expression checks whether a
variable(s), called the loop control variable (LCV), satisfies certain conditions. For example,
in Example 5-1, the expression in the while statement checks whether i <= 20 .(Recall
that in Java, when variables are declared, they are not automatically initialized.) The LCV
must be properly initialized before the while loop, and its value should eventually make the
logical expression evaluate to false .WedothisbyupdatingtheLCVinthebodyof
the while loop. Therefore, while loops are typically written in the following form:
//initialize the loop control variable(s)
while (logical expression)
//expression tests the LCV
{
.
.
.
//update the loop control variable(s)
.
.
.
}
For instance, in Example 5-1, the statement in Line 1 initializes the LCV i to 0 . The
expression i <= 20 in Line 2 checks whether i is less than or equal to 20 , and the
statement in Line 4 updates the value of i .
EXAMPLE 5-2
Consider the following Java program segment:
int i = 20;
//Line 1
while (i < 20)
//Line 2
{
System.out.print(i + " ");
//Line 3
i = i + 5;
//Line 4
}
System.out.println();
//Line 5
It is easy to overlook the difference between this example and Example 5-1. Here, in
Line 1, i is set to 20 . Because i is 20 , the expression i < 20 in the while statement
(Line 2) evaluates to false . Initially, the loop entry condition, i < 20 ,is false ,so
the body of the while loop never executes. Hence, no values are output and the value
of i remains 20 .
 
 
Search WWH ::




Custom Search