Java for Loop

Naveen AnamaneniUpdated · 5 min read

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

Laps.java▶ Try it
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");
    }
}
Output
Lap 1 done
Lap 2 done
Lap 3 done
Lap 4 done
Lap 5 done
Training over
PartIn this loopRuns
1. Initializationint lap = 1Once, before anything else
2. Conditionlap <= 5Before every round; false ends the loop
3. Bodythe printlnEach round, while the condition is true
4. Updatelap++After every round, then back to the condition

The Order They Run In

Initialize once, then check, run, update, check again
  1. Initialize once: lap = 1.
  2. Check the condition: 1 <= 5 is true.
  3. Run the body.
  4. Update: lap becomes 2.
  5. Back to step 2. When lap becomes 6, 6 <= 5 is false, and the loop ends.

Counting in Different Ways

Counting.java▶ Try it
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();
    }
}
Output
10 7 4 1
0 5 10 15 20
ABCDE

How it works

  1. Line 3 counts down in steps of 3: the update can be any change, here i -= 3.
  2. Line 7 counts up in steps of 5.
  3. Line 11 loops over characters, because a char is 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:

Total.java▶ Try it
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);
    }
}
Output
Pocket money saved: Rs. 1400

Day 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

  1. Easy: Print the even numbers from 2 to 20 on one line.
  2. Harder: Work out the factorial of 10 (1 × 2 × ... × 10) with a for loop. Which type do you need for the result, and why?

Quick check: for loop

4 questions
1Which part of a for loop runs only once?
2How many times does for (int i = 0; i <= 5; i++) run?
3When is the update (i++) run?
4What does for (int i = 5; i < 5; i++) print in its body?

Key Takeaways

Was this tutorial helpful?

Lesson 57 of 482