Java Reference
In-Depth Information
Lines 3 and 4. The statement in Line 3 outputs the value of i , which is 0 ; the statement in
Line 4 changes the value of i to 5 . After executing the statements in Lines 3 and 4, the
logical expression in the while loop (Line 2) is evaluated again. Because i is 5 , the
expression i <= 20 evaluates to true and the body of the while loop executes again.
This process of evaluating the logical expression and executing the body of the while
loop continues until the expression i <= 20 (Line 2) no longer evaluates to true .
The variable i (Line 2) in the expression is called the loop control variable.
Note the following from the preceding example:
1. Eventually, within the loop, i becomes 25 , but is not printed because
the entry condition is false .
5
2.
If you omit the statement:
i = i + 5;
from the body of the loop, you will have an infinite loop, continually
printing rows of zeros.
3. You must initialize the loop control variable i before you execute the
loop. If the statement:
i = 0;
(in Line 1) is omitted, either the compiler will generate an error or the
loop might not execute at all. (Recall that not all variables in Java are
automatically initialized.)
4.
In the previous program segment, if the two statements in the body of
the loop are interchanged, the result may be altered. For example,
consider the following statements:
int i = 0;
while (i <= 20)
{
i = i + 5;
System.out.print(i + " ");
}
System.out.println();
Here, the output is:
5 10 15 20 25
Typically, this would be a semantic error because you rarely want a condition to
be true for i <= 20 , and yet produce results for i > 20 .
Search WWH ::




Custom Search