Java Reference
In-Depth Information
x= 0;
x= x + 1 * 1;
x= x - 2 * 2;
...
x= x + 20 * 20;
x= x - 21 * 21;
x= x + 22 * 22;
Thus, we write the following loop (with initialization):
x= 0;
for ( int k= 1; k <= 22; k= k + 1) {
if (k%2==0) {
x= x-k*k;
} else {
x= x+k*k;
}
}
The general for-loop
We have shown the use of the for-loop to process a range of the integers.
That should be enough for now, and the following may be skipped. The general
for-loop is discussed in Chap. 7. However, for those who want to know a bit
more at this point, we discuss the for-loop further here.
The general form of the for-loop is
for ( initialization ; condition ; increment ) repetend
where
The initialization is an assignment to the control variable , including,
optionally, its declaration.
The condition is a boolean expression.
The increment is generally an assignment (without a semicolon) to the
control variable.
The repetend is any statement —usually a block.
Execution of the for-loop can be explained by the following flow chart
initialization
true
condition
repetend
increment
false
As an example, we write a loop (with initialization) that sums the even pos-
itive integers 2 , 4 , ... until the sum gets over 500 .
Search WWH ::




Custom Search