Java Reference
In-Depth Information
logical
expression
true
statement
false
FIGURE 5-1 while loop
The logical expression provides an entry condition. If it initially evaluates to true ,
the statement executes. The loop condition—the logical expression —is then
reevaluated. If it again evaluates to true , the statement executes again. The
statement (body of the loop) continues to execute until the logical expression is
no longer true . A loop that continues to execute endlessly is called an infinite loop.
To avoid an infinite loop, make sure that the loop's body contains one or more
statements that ensure that the loop condition—the logical expression in the while
statement—will eventually be false .
EXAMPLE 5-1
Consider the following Java program segment:
int i = 0;
//Line 1
while (i <= 20)
//Line 2
{
System.out.print(i + " ");
//Line 3
i = i + 5;
//Line 4
}
System.out.println();
//Line 5
Sample Run:
0 5 10 15 20
In Line 1, the variable i is set to 0 . The logical expression in the while statement (in Line 2),
i <= 20 , is then evaluated. Because the expression i <= 20 evaluates to true , the body of
the while loop executes next. The body of the while loop consists of the statements in
 
Search WWH ::




Custom Search