๐ŸŽ“ A1Learner
๐Ÿ”
0 of 48 lessons completed

Java For Loop

A for loop is a loop that gathers its start, its condition, and its change in one header. The header sits in parentheses after the for keyword.

Count by twos

The change part adds 2 on each pass. The counter prints the even numbers from 0 to 6.

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

Count down

The counter starts at 3. The change part subtracts 1 on each pass.

public class Main {
  public static void main(String[] args) {
    for (int i = 3; i > 0; i--) {
      System.out.println(i);
    }
  }
}

Nested loops print a grid

The outer loop makes one row on each pass. The inner loop prints three stars for that row.

public class Main {
  public static void main(String[] args) {
    for (int row = 0; row < 3; row++) {
      for (int col = 0; col < 3; col++) {
        System.out.print("*");
      }
      System.out.println();
    }
  }
}

Example

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

Key points

  • The header holds three parts separated by semicolons.
  • The first part sets the starting value.
  • The second part is the condition, checked before each pass.
  • The third part changes the counter after each pass.
  • A loop inside another loop is a nested loop.

In this example, i runs from 1 to 5. Each pass builds one line of the 7 times table. The product part multiplies 7 by the current value of i. The five lines print the products in order.

Note

A for loop fits well when the number of passes is known in advance.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which part of a for header is checked before each pass?