Understanding Java Nested Loops with Examples

Beantwortet mit GPT-4o-mini von Java Q&A Hub

Frage:

Introduce Java Nested Loops and give examples

Antwort:

In Java, nested loops are loops that exist within another loop. This structure allows you to perform more complex iterations, such as iterating over multi-dimensional data structures (like arrays or matrices) or performing repeated actions for each iteration of an outer loop.

Basic Structure of Nested Loops

The general structure of nested loops in Java can be illustrated as follows:

for (initialization; condition; update) {
    // Outer loop code
    for (initialization; condition; update) {
        // Inner loop code
    }
    // More outer loop code
}

Example 1: Nested For Loops

Here’s a simple example that uses nested for loops to print a multiplication table:

public class MultiplicationTable {
    public static void main(String[] args) {
        int rows = 10; // Number of rows
        int columns = 10; // Number of columns

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= columns; j++) {
                System.out.print(i * j + "\t"); // Print the product
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}

Output:

1	2	3	4	5	6	7	8	9	10	
2	4	6	8	10	12	14	16	18	20	
3	6	9	12	15	18	21	24	27	30	
...
10	20	30	40	50	60	70	80	90	100	

Example 2: Nested While Loops

You can also use nested while loops. Here’s an example that prints a pattern of stars:

public class StarPattern {
    public static void main(String[] args) {
        int rows = 5; // Number of rows

        int i = 1;
        while (i <= rows) {
            int j = 1;
            while (j <= i) {
                System.out.print("* "); // Print star
                j++;
            }
            System.out.println(); // Move to the next line after each row
            i++;
        }
    }
}

Output:

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

Example 3: Nested For-Each Loops

You can also use nested for-each loops to iterate over multi-dimensional arrays. Here’s an example that prints the elements of a 2D array:

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

        for (int[] row : array) {
            for (int element : row) {
                System.out.print(element + " "); // Print each element
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}

Output:

1 2 3 
4 5 6 
7 8 9 

Conclusion

Nested loops are a powerful feature in Java that allow you to handle complex data structures and perform repetitive tasks efficiently. However, it's important to be cautious with nested loops, as they can lead to increased time complexity, especially with deep nesting or large datasets.