JB Header

Java for Loop Tutorial with Examples

Introduction Computers are good at repeating work, and loops are how a program repeats a block of code. The for loop is the loop to use when you know how many times something should repeat - count from 1 to 10, go through each position of an array, or run a calculation for each year of a loan. This tutorial explains the Java for loop with examples. We will start with its syntax, and trace exactly how it runs. We will then count up, down and in steps, and use a loop to calculate totals. Next we will nest loops to print patterns and tables. Lastly, we will look at the variations of the loop header, and the most common for loop mistakes.

(Note - Loops use the comparison and increment operators from Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators and Increment/Decrement OperatorsClick to read tutorial: Java Assignment, Increment/Decrement and Ternary Operators.) Syntax of the for loop
for (initialization; condition; update) { body }
Where,
  • initialization runs once, before the loop starts. It usually declares a loop counter, such as int i = 1.
  • condition is checked before every repetition (iteration). If it is true, the body runs; if it is false, the loop ends.
  • update runs after every iteration, usually moving the counter on, such as i++.
  • body is the block of code to repeat.
A simple for loop
//CountToFive.java
public class CountToFive {
  public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {
      System.out.println("Iteration " + i);
    }
    System.out.println("Loop finished");
  }
}
 OUTPUT of the above code
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Loop finished
How the loop runs, step by step
  1. int i = 1 runs once.
  2. i <= 5 is checked: 1 <= 5 is true, so the body prints Iteration 1.
  3. i++ makes i 2, and the condition is checked again - and so on.
  4. After the fifth iteration, i++ makes i 6. 6 <= 5 is false, so the loop ends and the program continues with Loop finished.
The counter i is declared in the loop header, so it exists only inside the loop. If the condition is false from the start, the body never runs at all.
Counting up, down and in steps The update can change the counter in any way - count down with i--, or step by more than one with i += 2.
Counting down and in steps
//CountingLoops.java
public class CountingLoops {
  public static void main(String[] args) {
    System.out.print("Countdown: ");
    for (int i = 5; i >= 1; i--) {
      System.out.print(i + " ");
    }
    System.out.println("Lift off!");

    System.out.print("Even numbers: ");
    for (int i = 0; i <= 10; i += 2) {
      System.out.print(i + " ");
    }
    System.out.println();

    System.out.print("Powers of 2: ");
    for (int p = 1; p <= 1000; p *= 2) {
      System.out.print(p + " ");
    }
    System.out.println();

    System.out.print("Letters: ");
    for (char c = 'a'; c <= 'e'; c++) {
      System.out.print(c);
    }
    System.out.println();
  }
}
 OUTPUT of the above code
Countdown: 5 4 3 2 1 Lift off!
Even numbers: 0 2 4 6 8 10
Powers of 2: 1 2 4 8 16 32 64 128 256 512
Letters: abcde
Calculating with a loop A loop often builds up a result - a sum, a product or a count - in a variable declared before the loop, so that it still exists afterwards. Here, a loop calculates a factorial, and another one shows how savings grow with interest, year by year.
Totals and running calculations with for loops
//LoopCalculations.java
public class LoopCalculations {
  public static void main(String[] args) {
    int n = 10;
    long factorial = 1;
    for (int i = 2; i <= n; i++) {
      factorial *= i;
    }
    System.out.println(n + "! = " + factorial);

    double balance = 1000.0;
    double rate = 0.05;
    for (int year = 1; year <= 5; year++) {
      balance += balance * rate;
      System.out.printf("Year %d: %.2f%n", year, balance);
    }

    int[] scores = {72, 85, 90, 64, 88};
    int total = 0;
    for (int i = 0; i < scores.length; i++) {
      total += scores[i];
    }
    System.out.println("Average score: " + (double) total / scores.length);
  }
}
 OUTPUT of the above code
10! = 3628800
Year 1: 1050.00
Year 2: 1102.50
Year 3: 1157.63
Year 4: 1215.51
Year 5: 1276.28
Average score: 79.8
Explanation of the code
Nested for loops A loop can contain another loop. The inner loop runs completely for each iteration of the outer loop. Nested loops are used for rows and columns - tables, grids, two-dimensional arrays and patterns.
Nested for loops - a table and a pattern
//NestedLoops.java
public class NestedLoops {
  public static void main(String[] args) {
    for (int row = 1; row <= 4; row++) {
      for (int col = 1; col <= 4; col++) {
        System.out.printf("%4d", row * col);
      }
      System.out.println();
    }
    System.out.println();

    int height = 4;
    for (int row = 1; row <= height; row++) {
      System.out.print(" ".repeat(height - row));
      for (int star = 1; star <= 2 * row - 1; star++) {
        System.out.print("*");
      }
      System.out.println();
    }
  }
}
 OUTPUT of the above code
   1   2   3   4
   2   4   6   8
   3   6   9  12
   4   8  12  16

   *
  ***
 *****
*******
In the multiplication table, the outer loop chooses the row and the inner loop prints each column of that row, so the inner body runs 4 × 4 = 16 times in total. In the triangle, the number of stars depends on the row number. Variations of the loop header
  • Several variables: the initialization and update can contain several parts, separated by commas - for (int i = 0, j = 10; i < j; i++, j--) moves two counters towards each other.
  • Optional parts: any of the three parts can be left out. for (; i < 10; ) works like a while loop.
  • Infinite loop: for (;;) has no condition, so it repeats forever, until a break or return inside the body ends it. See break and continueClick to read tutorial: Java break, continue and Labeled Loops Explained.
A for loop with two counters
//TwoCounters.java
public class TwoCounters {
  public static void main(String[] args) {
    String word = "level";
    boolean palindrome = true;
    for (int i = 0, j = word.length() - 1; i < j; i++, j--) {
      if (word.charAt(i) != word.charAt(j)) {
        palindrome = false;
      }
    }
    System.out.println(word + " is a palindrome: " + palindrome);
  }
}
 OUTPUT of the above code
level is a palindrome: true
Common for loop mistakes
  • Off-by-one errors: running one time too many or too few. i <= array.length goes one position past the end of an array and throws an ArrayIndexOutOfBoundsException. Check where the counter starts and whether the condition should use < or <=.
  • A semicolon after the header: for (int i = 0; i < 5; i++); has an empty body. The loop runs five times doing nothing, and the block after it runs once.
  • An update that never reaches the end: for (int i = 0; i < 10; i--) moves away from the end and loops (practically) forever.
  • Changing the counter inside the body: it makes the loop hard to follow. Let the update part be the only place the counter changes.
Summary In this tutorial we first looked at the syntax of the for loop - initialization, condition and update - and traced exactly how it runs. We then counted up, down, in steps and through characters, and used loops to calculate a factorial, compound interest and an average. Next we nested loops to print a multiplication table and a triangle pattern. We then looked at variations of the loop header, such as two counters and optional parts. Lastly, we went through common mistakes, such as off-by-one errors and a stray semicolon. In the next tutorial, we will look at loops which run while a condition holds - the while and do-while loopsClick to read tutorial: Java while and do-while Loops with Examples.