Sub topic 2
Initialize, test, and update with for
A loop repeats a set of statements. An iteration is one pass through those statements. A for loop is useful when you know how many times to repeat.
The parts of a for loop
Save this program as Counting.java, then run it with javac Counting.java and java Counting.
public class Counting {
public static void main(String[] args) {
int visits = 0;
for (int i = 0; i < 3; i++) {
System.out.println(i);
visits++;
}
System.out.println("Visits: " + visits);
}
}The loop prints 0, 1, and 2. Then the program prints Visits: 3.
The for header has three parts, separated by semicolons:
int i = 0creates the counting variable and gives it a starting value. This happens once.i < 3is the condition, a test that is true or false. Java checks it before each iteration.i++adds one toi. This update happens after each iteration.
The statements inside the loop’s braces are its body. When the condition becomes false, Java stops the loop. If the condition is false at the first test, the body does not run at all.
Loop variable scope
Scope is the part of a program where a variable can be used. The variable i is declared in the for header, so it can be used in the header and body. It cannot be used after the loop.
The variable visits is declared before the loop. It can be used inside the loop and afterward, so the last line can print its value.
Visit array elements
An array holds a group of values. Each value is an element. An enhanced for loop visits each element without needing its position, or index.
Save this program as ArrayVisit.java and run it.
public class ArrayVisit {
public static void main(String[] args) {
int[] values = {4, 7, 9};
for (int value : values) {
System.out.println(value);
}
}
}The loop gives value each element in order. It prints 4, 7, and 9. The variable value is available inside the loop, but not after it. Use a basic for loop when you need an index.
Exercise
What does a loop with the header for (int n = 1; n <= 3; n++) print if its body prints n? Can you use n after the loop?
Show answer
It prints 1, 2, and 3. You cannot use n after the loop because its scope is limited to the loop.