Topic 4.14 — Enhanced for Loop for 2D Arrays
Goal: use the enhanced for loop (for-each) to traverse 2D arrays, understand what each loop variable represents, and know when you need indexed loops instead.
The big idea
For a 2D array, the enhanced for loop is usually two enhanced loops: one for each row (which is itself an array), and one for each element in the row.
It’s perfect for reading all values (sum/count/max), but not great when you need row/col indexes.
Syntax (2D)
for (Type[] row : grid) {
for (Type value : row) {
// use value
}
}
The first loop gives you each row array. The second loop gives you each element.
Example: print every value
for (int[] row : grid) {
for (int x : row) {
System.out.print(x + " ");
}
System.out.println();
}
Great use: sum / count / max
// sum
int sum = 0;
for (int[] row : grid) {
for (int x : row) {
sum += x;
}
}
// count negatives
int neg = 0;
for (int[] row : grid) {
for (int x : row) {
if (x < 0) neg++;
}
}
// max (assume grid has at least 1 element)
int max = grid[0][0];
for (int[] row : grid) {
for (int x : row) {
if (x > max) max = x;
}
}
Limitation: you don’t get indexes
In a for-each loop, you don’t directly know r and c.
If you need coordinates (like “row 2 col 3”), use indexed loops.
// Need row/col? Use indexes:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
// grid[r][c] with (r,c)
}
}
Updating is tricky
Assigning to the loop variable won’t update the array element.
for (int[] row : grid) {
for (int x : row) {
x = 0; // ❌ does not change grid
}
}
If you need to change values, use indexed loops and assign to grid[r][c].
Safe with jagged arrays
Enhanced loops naturally handle jagged arrays because each row has its own length.
for (int[] row : jagged) {
for (int x : row) {
// works even if rows have different lengths
}
}
Quick self-check
- In
for (int[] row : grid), what isrow? - In the inner loop, what does
xrepresent? - Why is for-each good for summing/counting?
- Why is for-each not ideal when you need row/col positions?
- How do you correctly update every element in a 2D array?