Nested loops allow one sequence of loops to be executed inside another. They are used when it is necessary to iterate over multidimensional structures, such as two-dimensional arrays or combinations of elements. The first loop is called the outer loop, and the one inside is called the inner loop.
The need to work with nested structures, such as matrices or graphs, led to the emergence of nested loops. Programming languages, including Java, initially support such a mechanism to program tasks related to processing arrays, graphs, grids, etc.
Using nested loops can lead to high time complexity if the number of iterations is not taken into account. Issues with code readability and indexing errors often arise. Improper use leads to repeated execution of the same actions.
Example code:
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); }
Key features:
Can both loops be exited at once with break?
The regular break statement only exits the inner loop. To exit multiple loops at once, labels are used:
outer: for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (condition) break outer; } }
Is it possible to have an infinite loop due to nested loops?
Yes, if the exit condition of any of the loops is incorrectly implemented, an infinite loop can result. This often occurs due to errors in initialization or counter incrementing.
Can the outer loop variables be modified from within the inner loop?
Yes, technically it is possible, but it significantly reduces readability and can lead to errors. It is better to avoid this and clearly separate the work of each loop.
Iterating through a two-dimensional array, but instead of i and j, i is used everywhere:
for (int i = 0; i < n; i++) { for (int i = 0; i < m; i++) {...} }
Pros:
Cons:
Using different variable names:
for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) {...} }
Pros:
Cons: