Java for Loop
A school PT teacher says, "Run five laps." You start counting at 1, check whether you've reached 5, run a lap, add one to the count, and check again. Every step of that is in Java's for loop, all on one line. It's the loop to use when you know, before starting, how many times something should repeat.
The Four Parts
public class Laps {
public static void main(String[] args) {
for (int lap = 1; lap <= 5; lap++) {
System.out.println("Lap " + lap + " done");
}
System.out.println("Training over");
}
}Lap 1 done
Lap 2 done
Lap 3 done
Lap 4 done
Lap 5 done
Training over| Part | In this loop | Runs |
|---|---|---|
| 1. Initialization | int lap = 1 | Once, before anything else |
| 2. Condition | lap <= 5 | Before every round; false ends the loop |
| 3. Body | the println | Each round, while the condition is true |
| 4. Update | lap++ | After every round, then back to the condition |
The Order They Run In
- Initialize once:
lap = 1. - Check the condition:
1 <= 5is true. - Run the body.
- Update:
lapbecomes 2. - Back to step 2. When
lapbecomes 6,6 <= 5is false, and the loop ends.
Counting in Different Ways
public class Counting {
public static void main(String[] args) {
for (int i = 10; i >= 1; i -= 3) {
System.out.print(i + " ");
}
System.out.println();
for (int floor = 0; floor <= 20; floor += 5) {
System.out.print(floor + " ");
}
System.out.println();
for (char c = 'A'; c <= 'E'; c++) {
System.out.print(c);
}
System.out.println();
}
}10 7 4 1
0 5 10 15 20
ABCDEHow it works
- Line 3 counts down in steps of 3: the update can be any change, here
i -= 3. - Line 7 counts up in steps of 5.
- Line 11 loops over characters, because a
charis a number underneath.
Try it yourself: print the 7 times table, from 7 x 1 = 7 to 7 x 10 = 70.
A Real Use: Adding Up
Loops often build a total, one round at a time:
public class Total {
public static void main(String[] args) {
int total = 0;
for (int day = 1; day <= 7; day++) {
total += day * 50;
}
System.out.println("Pocket money saved: Rs. " + total);
}
}Pocket money saved: Rs. 1400Day 1 adds 50, day 2 adds 100, and so on up to day 7, which adds 350: 50 + 100 + ... + 350 = 1,400. The variable total is declared before the loop, so it keeps its value between rounds and is still there afterwards.
Common Mistakes
A semicolon after the header. for (int i = 0; i < 5; i++); has an empty body. The block below it then runs once, after the loop.
Using the loop variable after the loop. i exists only inside the loop. Declare it before the loop if you need it afterwards.
Changing the loop variable inside the body. Adding to i in the body as well as in the update makes the loop hard to follow, and easy to break.
Practice
- Easy: Print the even numbers from 2 to 20 on one line.
- Harder: Work out the factorial of 10 (1 × 2 × ... × 10) with a
forloop. Which type do you need for the result, and why?
Key Takeaways
Was this tutorial helpful?