Accessing Elements in 2D Arrays
What you'll learn: How to read and write individual values in a two-dimensional array using row and column indices.
The Double-Index Syntax
Now that you can declare and initialize 2D arrays, you need to know how to actually get to the data inside them. Just like a single array uses one index (array[3]), a 2D array uses two indices: one for the row and one for the column.
The syntax is:
array[rowIndex][columnIndex]
Think of it like coordinates on a grid: you first specify which row you want, then which column within that row.
Reading Elements
To retrieve a value from a 2D array:
int[][] grid = {
{10, 20, 30},
{40, 50, 60}
};
int value = grid[0][1]; // Gets the element at row 0, column 1
// value is now 20
The first bracket [0] selects the first row {10, 20, 30}, and the second bracket [1] selects the second element from that row, which is 20.
Writing Elements
To change a value, use the same syntax on the left side of an assignment:
grid[1][2] = 99; // Changes row 1, column 2 from 60 to 99
// grid is now {{10, 20, 30}, {40, 50, 99}}
Analogy: Row and Seat Number
Imagine a movie theater. The row number gets you to the right aisle, and the seat number gets you to your specific chair. Similarly, array[row][col] first selects the row, then pinpoints the exact element within that row.
Key Takeaway: Access individual elements in a 2D array using double-bracket notation array[row][col] — the first index selects the row, the second selects the column within that row.