Java Reference
In-Depth Information
Placing Arithmetic Expressions in a for Statement's Header
The initialization, loop-continuation condition and increment portions of a for statement
can contain arithmetic expressions. For example, assume that x = 2 and y = 10 . If x and y
are not modified in the body of the loop, the statement
for ( int j = x; j <= 4 * x * y; j += y / x)
is equivalent to the statement
for ( int j = 2 ; j <= 80 ; j += 5 )
The increment of a for statement may also be negative , in which case it's a decrement , and
the loop counts downward .
Using a for Statement's Control Variable in the Statement's Body
Programs frequently display the control-variable value or use it in calculations in the loop
body, but this use is not required. The control variable is commonly used to control repe-
tition without being mentioned in the body of the for .
Error-Prevention Tip 5.5
Although the value of the control variable can be changed in the body of a for loop, avoid
doing so, because this practice can lead to subtle errors.
UML Activity Diagram for the for Statement
The for statement's UML activity diagram is similar to that of the while statement
(Fig. 4.6). Figure 5.4 shows the activity diagram of the for statement in Fig. 5.2. The
diagram makes it clear that initialization occurs once before the loop-continuation test is
evaluated the first time, and that incrementing occurs each time through the loop after the
body statement executes.
Initialize
control variable
int counter = 1
[counter <= 10]
Display the
counter value
Increment the
control variable
[counter > 10]
Determine whether
looping should
continue
counter++
System.out.printf( “%d ” , counter);
Fig. 5.4 | UML activity diagram for the for statement in Fig. 5.2.
 
 
Search WWH ::




Custom Search