Nested Loops in Java


In programming, a loop is used to repeat a block of code multiple times based on a given condition. A nested loop in Java refers to placing one loop inside another, allowing you to perform more complex iterations. Nested loops are commonly used in scenarios where you need to perform operations on a multi-dimensional data structure, such as a 2D array, or when dealing with tasks that involve repeating an action multiple times within another repeated action.


What is a Nested Loop in Java?

A nested loop is simply a loop within another loop. The inner loop runs completely for each iteration of the outer loop. This means that the inner loop’s code block will be executed multiple times for each single execution of the outer loop.

Types of Loops in Java:

Java provides three types of loops:

  1. for loop
  2. while loop
  3. do-while loop

All of these loops can be nested inside each other, allowing for flexible control over iterations.

Example of a Nested Loop

Consider the scenario where you want to print a pattern like a multiplication table or a grid. To do this, you can use nested loops to handle the rows and columns of the table.


Syntax of Nested Loops in Java

1. Nested for Loops

A nested for loop is a loop inside another for loop. The outer loop controls the number of rows, while the inner loop controls the columns.

Example: Simple Multiplication Table using Nested for Loops

public class NestedForLoopExample {
    public static void main(String[] args) {
        int rows = 5;
        int columns = 5;

        // Outer loop for rows
        for (int i = 1; i <= rows; i++) {
            // Inner loop for columns
            for (int j = 1; j <= columns; j++) {
                System.out.print(i * j + "\t");  // Multiply row and column numbers
            }
            System.out.println();  // Move to the next line after each row
        }
    }
}

Explanation:

  • The outer loop (for (int i = 1; i <= rows; i++)) iterates over the rows.
  • The inner loop (for (int j = 1; j <= columns; j++)) iterates over the columns.
  • The result is a multiplication table with 5 rows and 5 columns.

Output:

1	2	3	4	5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25	

2. Nested while Loops

A nested while loop works in a similar way to a for loop but with the condition-based iteration.

Example: Printing a Number Grid using Nested while Loops

public class NestedWhileLoopExample {
    public static void main(String[] args) {
        int rows = 3;
        int columns = 4;
        
        int i = 1;  // Outer loop control variable
        
        // Outer while loop for rows
        while (i <= rows) {
            int j = 1;  // Inner loop control variable
            
            // Inner while loop for columns
            while (j <= columns) {
                System.out.print(i + j + "\t");  // Sum of row and column indices
                j++;
            }
            
            System.out.println();  // Move to the next line after each row
            i++;
        }
    }
}

Explanation:

  • The outer while loop iterates over the rows.
  • The inner while loop iterates over the columns for each row.
  • The result is a grid where each element is the sum of its row and column indices.

Output:

2	3	4	5	
3	4	5	6	
4	5	6	7	

3. Nested do-while Loops

A nested do-while loop is another variant of a loop within a loop where the inner loop runs at least once, regardless of the condition.

Example: Nested do-while Loop Printing a Star Pattern

public class NestedDoWhileLoopExample {
    public static void main(String[] args) {
        int rows = 5;
        
        int i = 1;
        
        // Outer do-while loop for rows
        do {
            int j = 1;
            
            // Inner do-while loop for columns
            do {
                System.out.print("* ");
                j++;
            } while (j <= i);  // Inner loop runs i times
            
            System.out.println();  // Move to the next line after each row
            i++;
        } while (i <= rows);  // Outer loop runs rows times
    }
}

Explanation:

  • The outer do-while loop runs for each row.
  • The inner do-while loop runs a number of times equal to the current row number (i.e., i).
  • This prints a pyramid-like star pattern.

Output:

* 
* * 
* * * 
* * * * 
* * * * * 

Real-World Use Cases of Nested Loops

Nested loops are often used when working with multi-dimensional arrays, grids, matrices, or tables. Below are some common use cases:

1. Matrix Multiplication

When dealing with matrices, you often need to use nested loops to iterate over rows and columns to perform operations like matrix multiplication or matrix addition.

Example: Matrix Multiplication

public class MatrixMultiplicationExample {
    public static void main(String[] args) {
        int[][] matrixA = {{1, 2}, {3, 4}};
        int[][] matrixB = {{5, 6}, {7, 8}};
        
        int[][] result = new int[2][2];  // Resultant matrix
        
        // Outer loop for rows
        for (int i = 0; i < 2; i++) {
            // Inner loop for columns
            for (int j = 0; j < 2; j++) {
                for (int k = 0; k < 2; k++) {
                    result[i][j] += matrixA[i][k] * matrixB[k][j];
                }
            }
        }
        
        // Print the result matrix
        System.out.println("Result of Matrix Multiplication:");
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print(result[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Explanation:

  • Nested loops are used to multiply two 2x2 matrices and store the result.

Output:

Result of Matrix Multiplication:
19	22	
43	50	

2. Processing 2D Arrays

When working with 2D arrays (arrays of arrays), nested loops are a must. You use the outer loop for iterating over the rows and the inner loop for iterating over the columns.

Example: Traversing a 2D Array

public class Traverse2DArrayExample {
    public static void main(String[] args) {
        int[][] array = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Using nested for loops to traverse the 2D array
        for (int i = 0; i < array.length; i++) {  // Outer loop for rows
            for (int j = 0; j < array[i].length; j++) {  // Inner loop for columns
                System.out.print(array[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Explanation:

  • The outer loop iterates over the rows of the 2D array, and the inner loop iterates over each column within the current row.

Output:

1	2	3	
4	5	6	
7	8	9