Java Reference
In-Depth Information
Error-Prevention Tip 5.2
Using the final value and operator <= in a loop's condition helps avoid off-by-one errors.
For a loop that outputs 1 to 10, the loop-continuation condition should be counter <= 10
rather than counter < 10 (which causes an off-by-one error) or counter < 11 (which is cor-
rect). Many programmers prefer so-called zero-based counting, in which to count 10 times,
counter would be initialized to zero and the loop-continuation test would be counter < 10 .
Error-Prevention Tip 5.3
As Chapter 4 mentioned, integers can overflow, causing logic errors. A loop's control vari-
able also could overflow. Write your loop conditions carefully to prevent this.
A Closer Look at the for Statement's Header
Figure 5.3 takes a closer look at the for statement in Fig. 5.2. The first line—including
the keyword for and everything in parentheses after for (line 10 in Fig. 5.2)—is some-
times called the for statement header . The for header “does it all”—it specifies each item
needed for counter-controlled repetition with a control variable. If there's more than one
statement in the body of the for , braces are required to define the body of the loop.
for keyword
Control variable
Required semicolon
Required semicolon
for ( int counter = 1 ; counter <= 10 ; counter++)
Loop-continuation
condition
Incrementing of
control variable
Initial value of
control variable
o
Fig. 5.3 | for statement header components.
General Format of a for Statement
The general format of the for statement is
for ( initialization ; loopContinuationCondition ; increment )
statement
where the initialization expression names the loop's control variable and optionally provides
its initial value, loopContinuationCondition determines whether the loop should continue ex-
ecuting and increment modifies the control variable's value, so that the loop-continuation
condition eventually becomes false. The two semicolons in the for header are required. If
the loop-continuation condition is initially false , the program does not execute the for
statement's body. Instead, execution proceeds with the statement following the for .
Representing a for Statement with an Equivalent while Statement
The for statement often can be represented with an equivalent while statement as follows:
initialization ;
while ( loopContinuationCondition )
{
statement
increment ;
}
 
 
Search WWH ::




Custom Search