🌱BeginnerLoops

for Loop

Repeat code a fixed number of times with Java's for loop - the most common loop for counting and iteration.

Overview

A loop runs a block of code repeatedly until a condition becomes false. The for loop is ideal when you know exactly how many times you want to repeat something - iterating over array indices, counting up or down, or running code n times. A for loop has three parts in the header: initialisation (runs once at the start), condition (checked before each iteration), and update (runs after each iteration). All three are optional, but the semicolons are required.

Key Points

  • •Syntax: for (initialisation; condition; update) { ... }
  • •Initialisation runs once; condition is checked before each iteration; update runs after each body
  • •Loop exits when the condition becomes false
  • •Common pattern: for (int i = 0; i < n; i++) - iterates n times (i = 0, 1, ..., n-1)
  • •You can count down: for (int i = 10; i >= 0; i--)
  • •The loop variable (i) is local to the for loop and is not accessible after it

Examples

Basic for loop - print numbers 1 to 5

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
        // prints: 1, 2, 3, 4, 5
    }
}

i starts at 1, the loop runs while i <= 5, and i increases by 1 after each iteration.

Counting down and using the loop variable

public class Main {
    public static void main(String[] args) {
        // Count down from 5 to 1
        for (int i = 5; i >= 1; i--) {
            System.out.print(i + " ");
        }
        System.out.println("Go!");

        // Sum of 1 to 100
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        System.out.println("Sum: " + sum); // 5050
    }
}

The update i-- decrements by 1. You can also use i -= 2 to skip by twos.

Nested for loops - multiplication table

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.print(i * j + " ");
            }
            System.out.println(); // new line after each row
        }
        // Output:
        // 1 2 3
        // 2 4 6
        // 3 6 9
    }
}

The inner loop runs completely for each iteration of the outer loop.

Common Mistakes

  • Off-by-one error: `for (int i = 1; i < 5; i++)` runs 4 times (i=1,2,3,4); `i <= 5` runs 5 times
  • Accidentally modifying the loop counter inside the body - this makes loop behaviour unpredictable
  • Infinite loop: forgetting the update or writing a condition that never becomes false: `for (int i = 0; i >= 0; i++)`

Note

Use zero-based indexing (i = 0; i < n) when iterating arrays, since array indices start at 0. Use one-based (i = 1; i <= n) when printing user-visible numbers.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

How many times does this loop execute? `for (int i = 0; i < 5; i++)`