Sub topic 4
Initialize, test, and update with for
What a for loop does
A loop repeats a set of instructions. One pass through those instructions is called an iteration.
A Java for loop is useful when you know how you want to count through the repetitions. For example, you might want to print three numbers or add the numbers from 1 through 4.
A basic for loop brings three parts together:
- Initialization sets up the starting value.
- A condition decides whether another iteration can begin.
- An update changes a value after an iteration.
The condition is a test with a result of true or false. Java checks it before each iteration. If it is true, the loop runs its instructions. If it is false, the loop stops.
Run a first example
Save this complete program in a file named Main.java:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
}
}The main method is where this program starts. A method is a named set of instructions. Here, System.out.println prints a value and moves to a new line.
With the Java development tools installed, compile and run the program from the folder containing the file:
javac Main.java
java MainThe output is:
0
1
2The program prints three numbers. It starts at 0 and stops before printing 3.
Read the loop header
The line starting with for is the loop header. The header holds the three parts that control the loop:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
}
}Look at the text inside the parentheses:
| Part | Code | Job |
|---|---|---|
| Initialization | `int i = 0` | Create an integer variable named `i` and give it the value 0. |
| Condition | `i < 3` | Allow an iteration to begin only when `i` is less than 3. |
| Update | `i++` | Add 1 to `i` after an iteration. |
A variable is a named place to store a value. An integer is a whole number. The name i is often used for a counting variable, but you can choose a more descriptive name.
Two semicolons separate the three parts of the header. The instructions between the braces form the loop body. In this example, the body has one statement: System.out.println(i);. A statement is an instruction for Java to carry out.
The update i++ increases i by 1. In this header, it has the same effect as writing i = i + 1. For that assignment, Java finds the value of i + 1 and stores it back in i.
Follow the order of execution
The order of the three parts matters. Java does not run the header from left to right on every iteration.
- Run the initialization once.
- Check the condition.
- If the condition is
true, run the body. - Run the update.
- Go back to the condition.
- If the condition is
false, leave the loop and move to the next instruction after it.
The table follows each check of the condition:
| Value of `i` at the check | Is `i < 3` true? | What happens? |
|---|---|---|
| 0 | Yes | Print `0`, then update `i` to 1. |
| 1 | Yes | Print `1`, then update `i` to 2. |
| 2 | Yes | Print `2`, then update `i` to 3. |
| 3 | No | Leave the loop. |
The update makes i equal to 3, but the body does not print 3. Java checks the condition again first. Since 3 < 3 is false, the body does not run another time.
A loop can run zero times
Because Java checks the condition before the body, a for loop can skip its body altogether.
For example, suppose the header is for (int i = 3; i < 3; i++). The initialization sets i to 3. The first condition check is false, so the body does not run. The update does not run either.
This is useful when there may be no work to repeat. You do not need a separate instruction just to skip the loop in that case.
Choose the start and end
The start and the condition together decide which values reach the body.
| Header | Values used in the body | Number of iterations |
|---|---|---|
| `for (int i = 0; i < 3; i++)` | 0, 1, 2 | 3 |
| `for (int i = 1; i < 3; i++)` | 1, 2 | 2 |
| `for (int i = 1; i <= 3; i++)` | 1, 2, 3 | 3 |
| `for (int i = 3; i < 3; i++)` | None | 0 |
The symbol < means “less than.” The symbol <= means “less than or equal to.” Changing from < 3 to <= 3 allows the body to run when i is 3.
A useful pattern for repeating something a set number of times is to start at 0 and use < with that number. For example, i = 0 and i < 5 give five iterations: 0, 1, 2, 3, and 4.
If you want to print the numbers 1 through 5 instead, start at 1 and use i <= 5. That also gives five iterations, but the values are different.
Change the update
The update does not have to add 1. This program counts by twos:
public class Main {
public static void main(String[] args) {
for (int number = 2; number <= 8; number = number + 2) {
System.out.println(number);
}
}
}Save it as Main.java in place of the first example, then compile and run it in the same way. It prints:
2
4
6
8The variable number starts at 2. After each time the body prints it, the update adds 2. When number becomes 10, the condition number <= 8 is false, so the loop ends.
The update can also be written as number += 2. That is a shorter way to add 2 and store the result back in number. Both forms work in this loop.
The condition is checked against the actual values reached by the update. For example, if the end condition were number <= 7, this loop would print 2, 4, and 6. It would not print 7, because adding 2 to 6 gives 8.
Count down
A loop can move toward a smaller number instead. In this example, count-- subtracts 1 from count after each iteration:
public class Main {
public static void main(String[] args) {
for (int count = 3; count >= 1; count--) {
System.out.println(count);
}
System.out.println("Go!");
}
}The output is:
3
2
1
Go!The symbol >= means “greater than or equal to.” The condition stays true for 3, 2, and 1. After the update changes count from 1 to 0, the condition is false.
Notice where System.out.println("Go!"); sits: it is after the loop’s closing brace. The program prints Go! once, after the loop ends. The quotation marks mark Go! as text to print.
For a countdown, make sure the update moves the value down toward the end. If this example added 1 instead, the condition count >= 1 would keep being true as the count rose, for the ordinary values you would first see. The loop would not stop when intended.
Use a loop to build a total
A loop can do more than print its counting value. This program adds the numbers 1 through 4:
public class Main {
public static void main(String[] args) {
int total = 0;
for (int number = 1; number <= 4; number++) {
total = total + number;
}
System.out.println(total);
}
}The output is:
10The variable total starts at 0. Each time the body runs, it adds the current value of number to total and stores the result back in total.
| Iteration | `number` added | `total` after the addition |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
After the fourth iteration, the update changes number to 5. The condition number <= 4 is then false, so the loop ends. The final print statement runs once and prints the total.
Try moving the print statement into the loop body in your copy of the program. It will print the changing total after each addition: 1, 3, 6, and 10. Move it back after the loop to print only the final total.
Plan a for loop
When writing your own loop, decide what should happen before you choose the header.
- Choose the work to repeat. That work goes in the body.
- Choose a starting value for the counting variable.
- Decide which values should be allowed to reach the body. Write a condition that is true for those values.
- Choose an update that moves from one value to the next and eventually makes the condition false.
- Trace the first iteration and the last expected iteration.
For example, to print 5, 4, and 3, start at 5, use the condition count >= 3, and subtract 1 after each print. When the update reaches 2, the condition is false.
A for loop is a good fit for this kind of task because the start, test, and update are all visible in one header. As with a while loop, the test happens before the body. The for form is especially handy when the counting steps are clear from the start.
Exercises
Exercise
What does for (int i = 0; i < 4; i++) print if its body is System.out.println(i);?
Show answer
It prints 0, 1, 2, and 3, each on its own line. When i becomes 4, the condition is false.
Exercise
Change the condition in for (int i = 1; i < 4; i++) so that a body printing i also prints 4.
Show answer
Use i <= 4. The body then prints 1, 2, 3, and 4.
Exercise
A loop starts with int n = 2, uses the condition n <= 7, and updates with n = n + 2. What values reach its body?
Show answer
The values are 2, 4, and 6. The next update makes n 8, so the condition is false.
Exercise
Write a for loop that prints 3, 2, and 1 on separate lines.
Show answer
for (int count = 3; count >= 1; count--) { System.out.println(count); }
Exercise
In the total example, what value would be printed if the condition changed from number <= 4 to number < 4?
Show answer
It would print 6. The loop would add 1, 2, and 3, but not 4.