Java Reference
In-Depth Information
(1)
x= 0;
x= x+2*2;
x= x+3*3;
x= x+4*4;
…
x= x + 200 * 200;
200 lines is a lot to type. It would be nice to be able to paraphrase it like this:
For each number
i
in the range
2..200
, add
i*i
to
x
.
Here is a for-loop (preceded by an initializing declaration of
x
) that does just that:
(2) int
x= 0;
for
(
int
i= 2; i <= 200; i= i + 1) {
x= x+i*i;
}
Variable
i
is called the
loop counter
.
The constituents of this loop are:
•
The part of the loop within the parentheses:
- The initializing declaration of
int
variable
i
(initialized to 2);
- A semicolon;
- The loop-condition
i <= 200
. It can be any boolean expression;
- A semicolon;
- An assignment that adds
1
to loop counter
i
.
•
The block after the parentheses (the opening brace
{
followed by the
sequence of statements followed by the closing brace
}
) is called the
repetend
of the loop.
Repetend
means “the thing to be repeated”.
Program segment (2) performs exactly the same task as program segment (1)
above. It is just a shorthand version. Thus, sequence (2) executes
x= 0;
and then
executes the statement
x= x+i*i;
with
i
containing
2
, then with i containing
3
, and so on up to
i
containing
200
.
You can (and should) put that code in a method and step through it in your
debugger.
As a second example, we write a loop that performs the following assign-
ment:
x= 1 * 1 - 2 * 2 + 3 * 3 - 4 * 4 + … + 21 * 21 - 22 * 22;
Here, the squares of odd integers are added and the squares of even integers are
subtracted, so this assignment is equivalent to:
Search WWH ::
Custom Search