CodeBlanks Logo Icon CodeBlanks

The for loop

Learn counting loops with for.

The for loop

The for loop repeats a fixed number of times. It has three parts: init, condition and step.

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Here i starts at 0, repeats while it is below 5 and grows by 1 each step. The output is 0, 1, 2, 3, 4. i++ adds 1 to i each turn. When the condition is false, the loop ends.

for components

The three parts of a for loop are separated by semicolons: for (init; condition; step).

// Sum from 1 to 5
int sum = 0;
for (int i = 1; i <= 5; i++) {
    sum += i;
}
System.out.println(sum);  // 15

Init runs once, the condition is tested at the start of each turn, and the step runs at the end. i <= 5 includes equality, so the loop runs five times from 1 to 5.

Practice Print 1 to 5

Write a Main class with a main method. With for (int i = 1; i <= 5; i++) print each i using System.out.println(i).

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

Expected output

1
2
3
4
5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many times does for (int i = 0; i < 3; i++) { ... } run?

  • 2
  • 4
  • 3 Correct answer
  • Infinite

Explanation: It runs 3 times for i=0,1,2.

2 Complete the for loop

Question
for (int i = 0; i ____ 5; i++) {
    System.out.println(i);
}
Answer
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Explanation: i < 5 loops from 0 to 4.

3 Match the for concepts

Term Meaning
int i = 0 Init
i < 5 Condition
i++ Step
{ } Block

All lessons in Beginner