Decisions & Loops 🔁
beginner25 XP

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:

Java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Planting seed " + i);
        }
    }
}

Prints:

Code
Planting seed 1
Planting seed 2
Planting seed 3

The three parts of a for loop

for (int i = 1; i <= 3; i++)

PartMeaning
int i = 1start: make a counter called i, starting at 1
i <= 3keep going while this is true
i++after each lap, add 1 to i

🚀 Counting down

Loops can count backwards too:

Java
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:

Java
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.

Open the online Java editor ↗

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.

Quick check

01/6
How many times does for (int i = 1; i <= 4; i++) repeat?