Java Reference
In-Depth Information
8
int counter = 1 ; // declare and initialize control variable
9
10
while (
counter <= 10
) // loop-continuation condition
11
{
12
System.out.printf( "%d " , counter);
13
++counter; // increment control variable
14
}
15
16
System.out.println();
17
}
18
} // end class WhileCounter
1 2 3 4 5 6 7 8 9 10
Fig. 5.1 | Counter-controlled repetition with the while repetition statement. (Part 2 of 2.)
In Fig. 5.1, the elements of counter-controlled repetition are defined in lines 8, 10
and 13. Line 8 declares the control variable ( counter ) as an int , reserves space for it in
memory and sets its initial value to 1 . Variable counter also could have been declared and
initialized with the following local-variable declaration and assignment statements:
int counter; // declare counter
counter = 1 ; // initialize counter to 1
Line 12 displays control variable counter 's value during each iteration of the loop. Line
13 increments the control variable by 1 for each iteration of the loop. The loop-continua-
tion condition in the while (line 10) tests whether the value of the control variable is less
than or equal to 10 (the final value for which the condition is true ). The program per-
forms the body of this while even when the control variable is 10 . The loop terminates
when the control variable exceeds 10 (i.e., counter becomes 11 ).
Common Programming Error 5.1
Because floating-point values may be approximate, controlling loops with floating-point
variables may result in imprecise counter values and inaccurate termination tests.
Error-Prevention Tip 5.1
Use integers to control counting loops.
The program in Fig. 5.1 can be made more concise by initializing counter to 0 in line
8 and preincrementing counter in the while condition as follows:
while (++counter <= 10 ) // loop-continuation condition
System.out.printf( "%d " , counter);
This code saves a statement, because the while condition performs the increment before
testing the condition. (Recall from Section 4.13 that the precedence of ++ is higher than
that of <= .) Coding in such a condensed fashion takes practice, might make code more dif-
ficult to read, debug, modify and maintain, and typically should be avoided.
Software Engineering Observation 5.1
“Keep it simple” is good advice for most of the code you'll write.
 
Search WWH ::




Custom Search