 |
For loops
|
-
One common loop pattern involves initializing a variable, and then updating
it each iteration, until a condition is reached.
-
Because this loop is so common, Java (and other languages) provide a special
loop statement
The for loop
-
The structure of a for loop is as follows:
for (initialization; loop condition; increment) {
body
}
The initialization part is performed once before the loop condition
is checked for the first time.
The loop condition and body play the same role as for the
while statement.
The increment is executed each time after the body
is executed, but before the loop condition is checked.
We can translate a for loop into a while loop in the following way:
initialization;
while (loop condition) {
body
increment
}
Example:
-
Sum all the numbers between 1 and 10
int i;
int sum = 0;
for (i=1; i<=10; i++) {
sum += i;
}
Note that i++ is equivalent to i += 1
Note that any number of initializations and increments can occur in the
appropriate parts of the for loop
-
each separate initialization or increment must be separated by a comma
int i;
int sum;
for (i=1, sum=0; i<=10; sum+=i, i++)
The above loop also sums the numbers between 1 and 10.
Exercises
-
Write a for loop that calculates 2 to the power of x (i.e., 2 * 2 * 2 *
... * 2, x times).
-
Write a for loop that reads in 10 integers from the keyboard, and sums
them.
Last modified: 4/5/99