Course contentsShow
← Computer Science
Lesson 243 of 2,8726. Arrays and Basic CollectionsFree lesson

Indexing and Accessing 2D Arrays

Learn to access elements using row and column indices, understand zero-based indexing in two dimensions.

Indexing and Accessing 2D Arrays

You'll learn how to pinpoint and retrieve specific elements in a 2D array using row and column coordinates.

The Core Idea

A 2D array is like a grid or spreadsheet with rows and columns. To access any element, you need two indices: one for the row and one for the column. Just like arrays you've already learned, 2D arrays use zero-based indexing in both dimensions—meaning the first row is row 0, the first column is column 0, and so on.

Think of it like finding a seat in a movie theater. If someone tells you "Row 2, Seat 3," you know exactly where to sit. In programming, array[2][3] means "go to row 2, then move to column 3."

How It Works

The syntax is straightforward:

element = arrayName[rowIndex][columnIndex]

For example, if you have a 2D array called grid:

grid[0][0]  // top-left element (first row, first column)
grid[0][2]  // first row, third column
grid[1][0]  // second row, first column
grid[2][3]  // third row, fourth column

Visualizing the Indices

Imagine a 3×4 grid:

         col0  col1  col2  col3
row0  [  [0]   [1]   [2]   [3]  ]
row1  [  [0]   [1]   [2]   [3]  ]
row2  [  [0]   [1]   [2]   [3]  ]

To access the element at row 1, column 2, you write grid[1][2].

Setting Values

You can also assign values the same way:

grid[0][0] = 42     // sets top-left element
grid[2][1] = 99     // sets third row, second column

Key Takeaway: Access 2D array elements using array[row][column] with zero-based indexing—the first element is at [0][0], not [1][1].