for Loop

Syntax

Use a for loop when you know how many times to repeat.

for (initialisation; condition; update) {
    // repeated code
}
for (int i = 1; i <= 3; i++)
      |            |       |
      |            |       +-- 3. runs after each round
      |            +---------- 2. checked before each round
      +----------------------- 1. runs once at the start

Examples

Example

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

        for (int i = 10; i >= 0; i -= 2) {   // count down by 2
            System.out.print(i + " ");
        }
        System.out.println();

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

        int n = 7;
        for (int i = 1; i <= 5; i++) {
            System.out.println(n + " x " + i + " = " + n * i);
        }
    }
}

Output

1 2 3 4 5 
10 8 6 4 2 0 
Sum 1..100 = 5050
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

Practice

Exercise: Print the factorial of 6 (6! = 720) with a for loop.

Show answer
long fact = 1;
for (int i = 1; i <= 6; i++) {
    fact *= i;
}
System.out.println(fact);   // 720