Java for Beginners, Lesson 19: for Loop and Nested Loops (Patterns) in Java

Java for Beginners · Module 4: Control Flow


🎯 The Loop for Counting

When you know how many times to repeat, the for loop is the neatest choice. It puts the start, the condition and the update on a single line, so you can see the whole loop at a glance.

📌 for (init; condition; update) { body } : init runs once, then Java repeats: test the condition, run the body, run the update.

1️⃣ The for Loop

init
int i = 1 (once)
➜
condition
i <= 5 ?
true ➜
body
runs
➜
update
i++
back to condition
for (init; condition; update) { body }: all three control parts sit on one line.

Figure 1: The order of events in a for loop.

Program 1: Counting, summing and factorial

public class ForBasic {
    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) {
            System.out.print(i + " ");
        }
        System.out.println();

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

        int fact = 1;
        for (int k = 1; k <= 5; k++) {
            fact *= k;
        }
        System.out.println("5! = " + fact);
    }
}
🖥️ Output:
1 2 3 4 5
10 8 6 4 2 0
Sum 1..100 = 5050
5! = 120
  • Use print (without ln) to keep the numbers on one line, and a bare println() to end the line.
  • A loop can count down (i--) or step by any amount (i -= 2).
  • The loop variable int i is declared inside the for, so it exists only within the loop (Lesson 11). The same name can be reused in the next loop.
  • Accumulator pattern: start a variable (sum = 0, fact = 1) before the loop and update it each pass. For a sum the start is 0, and for a product the start is 1.

Program 2: A multiplication table

public class Table {
    public static void main(String[] args) {
        int n = 7;
        for (int i = 1; i <= 10; i++) {
            System.out.println(n + " x " + i + " = " + (n * i));
        }
    }
}
🖥️ Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

2️⃣ Other Shapes of for

public class ForEachAndMulti {
    public static void main(String[] args) {
        int[] marks = {70, 85, 90};
        int total = 0;
        for (int m : marks) {
            total += m;
        }
        System.out.println("Total = " + total);

        for (int i = 0, j = 10; i < j; i += 3, j -= 3) {
            System.out.println("i = " + i + ", j = " + j);
        }

        int count = 0;
        for (int a = 1; a <= 3; a++) {
            for (int b = 1; b <= 4; b++) {
                count++;
            }
        }
        System.out.println("Inner body ran " + count + " times");
    }
}
🖥️ Output:
Total = 245
i = 0, j = 10
i = 3, j = 7
Inner body ran 12 times
  • For-each loop: for (int m : marks) reads “for each m in marks”. It visits every element of an array without an index. Arrays come in Lesson 21.
  • You can run two variables together by separating them with commas in the init and update parts.
  • A loop inside a loop is a nested loop. The inner body runs (outer count × inner count) times: 3 × 4 = 12.

3️⃣ Nested Loops and Patterns

Printing patterns is the standard way to practise nested loops. Think of the output as a table: the outer loop chooses the row, and the inner loop prints along that row.

Outer rowInner loop runsPrints
11 time*
22 times* *
33 times* * *
44 times* * * *
The outer loop picks the row. The inner loop prints that row from start to finish before the outer loop moves on.

Figure 3: How a nested loop prints a triangle.

rowspaces beforestarswhat is printed
131   *
223  ***
315 *****
407*******
For 4 rows: spaces = 4 − row, stars = 2 × row − 1.

Figure 2: The formula behind the pyramid pattern.

Program 4: Four classic patterns

public class Patterns {
    public static void main(String[] args) {
        System.out.println("Right triangle:");
        for (int row = 1; row <= 4; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print("* ");
            }
            System.out.println();
        }

        System.out.println("Number triangle:");
        for (int row = 1; row <= 4; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print(col + " ");
            }
            System.out.println();
        }

        System.out.println("Pyramid:");
        for (int row = 1; row <= 4; row++) {
            for (int s = 1; s <= 4 - row; s++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= 2 * row - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }

        System.out.println("Square of letters:");
        for (int r = 0; r < 3; r++) {
            for (int c = 0; c < 4; c++) {
                System.out.print((char) ('A' + c));
            }
            System.out.println();
        }
    }
}
🖥️ Output:
Right triangle:
*
* *
* * *
* * * *
Number triangle:
1
1 2
1 2 3
1 2 3 4
Pyramid:
*
***
*****
*******
Square of letters:
ABCD
ABCD
ABCD
  • Right triangle: in row r, the inner loop runs r times, so it prints r stars. After each row, println() moves to the next line.
  • Number triangle: the same shape, but it prints the inner counter col instead of a star.
  • Pyramid: each row needs two inner loops, one for spaces (4 − row of them) and one for stars (2 × row − 1 of them).
  • Letters: (char) ('A' + c) turns the column number into a letter, using the char arithmetic from Lesson 8.
  • To design any pattern, write down for each row how many spaces and how many symbols it needs, then find the formula in terms of the row number.

4️⃣ Errors Beginners Meet

Commas instead of semicolons

public class Bad1 {
    public static void main(String[] args) {
        for (int i = 0; i < 3, i++) {
            System.out.println(i);
        }
    }
}
🖥️ Compiler message:
Bad1.java:3: error: ‘;’ expected
for (int i = 0; i < 3, i++) {
^
1 error
  • The three parts of a for loop are separated by semicolons.

Using the loop variable after the loop

public class Bad2 {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println(i);
        }
        System.out.println("Last i = " + i);
    }
}
🖥️ Compiler message:
Bad2.java:6: error: cannot find symbol
System.out.println(“Last i = ” + i);
^
symbol: variable i
location: class Bad2
  • i was declared inside the for, so it vanishes after the loop. Declare it before the loop if you need its final value.

⚠️ Common Mistakes

MistakeProblemFix
for (int i = 0; i < 3, i++)Comma instead of semicolonUse ;
for (...); with a semicolon at the endEmpty loop body; the block runs once afterRemove the ;
Off by one: i <= n versus i < nOne extra or one missing passTrace the first and last values
Starting a product at 0Result is always 0Start products at 1
Reusing the same variable in nested loopsInner loop disturbs the outerUse different names (row, col)
Forgetting println() after the inner loopEverything on one lineAdd it after the inner loop

❓ Frequently Asked Questions

Q1. When should I use for instead of while?
Use for when the count is known, and while when the loop depends on something that happens during the run.

Q2. Can any part of the for header be empty?
Yes. for (;;) is an infinite loop. You then need a break (Lesson 20).

Q3. Does a for loop run its update after the last pass?
Yes, the update runs after every body pass, then the condition is checked and fails.

Q4. How many times does a nested loop run?
Outer count × inner count, if the inner count does not change.

✅ Key Takeaways

  • for (init; condition; update) keeps the whole loop control on one line.
  • The init runs once. Then: test, body, update, repeat.
  • Use sum starting at 0 and product starting at 1 for the accumulator pattern.
  • For-each (for (int m : marks)) visits every element of an array.
  • Nested loops print patterns: the outer loop is the row, the inner loop is the column.
🎓 Practice questions: (1) Print the first 10 even numbers. (2) Print the Fibonacci series up to 10 terms. (3) Print an inverted triangle of stars with 5 rows. (4) Print the pattern with rows “1”, “2 2”, “3 3 3”, “4 4 4 4”. (5) Write a program that prints all prime numbers between 1 and 50 using a nested loop.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision