Java Reference
In-Depth Information
/** Draw n circles using Graphics g with centers (x, y)
and radii of 4 , 8 , 12 , …*/
int i= 0;
// { invariant: the i smallest circles have been drawn }
while (i != n) {
int r= 5 + 5 * i; // radius of circle i
g.drawOval(x - i, y - i, 2 * i, 2 * i);
i= i + 1;
}
This loop has a loop counter , i . A variable is a loop counter if (1) it is ini-
tialized just before the loop and (2) the repetend ends with a statement that
increments (or decrements) it.
Below, we rewrite the while-loop as a for-loop. The first line of the for-loop
(the line that begins with for ) contains the initialization, the loop condition, and
the increment of the loop counter (without the final semicolon!):
// Draw n circles with centers (x, y) and radii of 4 , 8 , 12 , …
// { invariant: the i smallest circles have been drawn }
for ( int i= 0; i != n; i= i + 1) {
int r= 5+5*i; // radius of circle i
g.drawOval(x - i, y - i, 2 * i, 2 * i);
}
The two program segments, one using a while-loop and one using a for-loop,
execute exactly the same way. The for-loop is more compact and has a different
feel to it. All the “control” part of the loop appears in the first line, and that makes
it easier to understand, for some. When looking at the repetend, for example, one
has to think of only one thing: how does it fix the invariant?
When you decide that a loop is needed in a program, if you can be positive
that the loop will have a loop counter, write the loop as a for-loop. However,
loops that do not have a loop counter are best written using a while-loop; and
forcing these loops into the for-loop format often results in awkward code.
7.5.2
Syntax and semantics of for-loops
Here is the syntax of a for-loop:
Activity
7-4.2
for ( initialization ; condition ; progress )
repetend
The initialization is an assignment to the loop counter. It can also contain a
declaration of the loop counter, if it has not been declared previously. But the
scope of the loop counter that is declared within the loop is just the for-loop
itself.
The condition is a boolean expression.
Style Note
13.2, 13.2.3
indenting
loops
Search WWH ::




Custom Search