for Loops: Repeat!
Plant rows, count laps and launch rockets with for loops.
for Loops: Repeat! 🔁
Robots are great at doing the same thing again and again without getting bored. A for loop repeats code a set number of times:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("Planting seed " + i);
}
}
}Prints:
Planting seed 1 Planting seed 2 Planting seed 3
The three parts of a for loop
for (int i = 1; i <= 3; i++)
| Part | Meaning |
|---|---|
int i = 1 | start: make a counter called i, starting at 1 |
i <= 3 | keep going while this is true |
i++ | after each lap, add 1 to i |
🚀 Counting down
Loops can count backwards too:
public class Main {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println("Liftoff!");
}
}Prints 5 4 3 2 1 Liftoff!
Adding things up
A loop plus a variable can total things:
public class Main {
public static void main(String[] args) {
int total = 0;
for (int day = 1; day <= 7; day++) {
total += 3; // 3 liters of water per day
}
System.out.println("Water this week: " + total + " liters");
}
}🐝 Fun fact
A honeybee may visit hundreds of flowers on a single trip. If a bee were a robot, its code would be one big loop: fly, find a flower, collect, repeat!
Want to run it yourself?
Predict what the code prints first, then check! Copy an example above, paste it into the free online Java editor, and press Run. Keep the first line as public class Main.
Opens Programiz, a free site that isn't run by First Coding Path and may show ads. Grown-ups, you might like to take a look first.