Iterating 2D Arrays with Nested Loops
What you'll learn: How to use nested for loops to visit every element in a two-dimensional array by traversing rows and columns systematically.
The Core Idea
A two-dimensional array is like a grid with rows and columns. To access every element, you need two loops: an outer loop that moves through each row, and an inner loop that moves through each column within that row. This nested structure mirrors the array's two-dimensional organization.
How Nested Loops Work
Think of reading a book: you process one line (row) at a time, reading each word (column) in that line before moving to the next line. Similarly:
- The outer loop controls which row you're examining
- The inner loop controls which column within that row you're accessing
int[][] grid = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println(); // New line after each row
}
Output:
10 20 30
40 50 60
70 80 90
Notice grid.length gives the number of rows, while grid[row].length gives the number of columns in that specific row (important for jagged arrays).
Processing Order
The loops visit elements in row-major order: all columns in row 0, then all columns in row 1, and so on.
Key Takeaway: Use nested for loops to iterate 2D arrays—the outer loop for rows, the inner loop for columns—ensuring you visit every element systematically.