Nested Loops

A Loop Inside a Loop

Example

The inner loop runs completely for every single round of the outer loop.

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

Output

1	2	3	4	
2	4	6	8	
3	6	9	12

Pattern Printing

Example

Pattern programs are classic interview and lab questions. They practise nested loops.

public class Main {
    public static void main(String[] args) {
        int n = 4;
        // right triangle
        for (int i = 1; i <= n; i++) {
            System.out.println("* ".repeat(i));
        }
        // pyramid
        for (int i = 1; i <= n; i++) {
            System.out.println(" ".repeat(n - i) + "*".repeat(2 * i - 1));
        }
        // number triangle
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }
}

Output

* 
* * 
* * * 
* * * * 
   *
  ***
 *****
*******
1
12
123
1234

Exercise: Print this pattern for n = 4 using nested loops:
4444
333
22
1

Show answer
for (int i = 4; i >= 1; i--) {
    for (int j = 1; j <= i; j++) {
        System.out.print(i);
    }
    System.out.println();
}