Lesson 6 | Nested Loops |

Objective | Application of Nested Loops |

Loops can be nested within each other. Any nested combination of the for, for-each, while, or do-while loops is permitted.
This is useful for addressing a number of problems. The example that follows computes the sum of the elements of a row in a
two-dimensional array. It starts by initializing each element to the sum of its indexes. The array is then displayed. This is followed by nested loops to compute and display
the sum of the elements for each row:

final int numberOfRows = 2; final int numberOfColumns = 3; int matrix[][] = new int[numberOfRows][numberOfColumns]; for (int i = 0; i lt; matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { matrix[i][j] = i + j; } } for (int i = 0; i < matrix.length; i++) { for(int element : matrix[i]) { System.out.print(element + " "); } System.out.println(); } for (int i = 0; i < matrix.length; i++) { int sum = 0; for(int element : matrix[i]) { sum += element; } System.out.println("Sum of row " + i + " is " +sum); }

Notice the use of the length method used to control the number of times the loops are executed. This makes the code more maintainable if the size of the arrays change. When executed we get the following output:

0 1 2 1 2 3 Sum of row 0 is 3 Sum of row 1 is 6

Notice the use of the for-each statement when the array is displayed and the sum of the rows are calculated. This simplifies the calculations. The break and continue statements can also be used within nested loops. However, they will only be used in conjunction with the current loop. That is, a break out of an inner loop will only break out of the inner loop and not the outer loop. As we will see in the next section, we can break out of the outer loop from an inner loop using labels. In the following modification of the last nested loop sequence, we break out of the inner loop when the sum exceeds 2:

for (int i = 0; i < matrix.length; i++) { int sum = 0; for(int element : matrix[i]) { sum += element; if(sum > 2) { break; } } System.out.println("Sum of row " + i + " is " +sum); }

The execution of this nested loop will change the sum of the last row as shown below:

Sum of row 0 is 3 Sum of row 1 is 3

The break statement took us out of the inner loop but not the outer loop. We can break out of the outer loop if there was a corresponding break statement within the immediate body of the outer loop. The continue statement behaves in a similar fashion in relation to inner and outer loops.