A girl and a robot thinking together

Think together · Start with a story

A girl finds a classmate by asking, “Which row and which seat?” That is how she locates an item in a table.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Row indexChoose a row
  2. Column indexChoose a position in that row
  3. ElementRead the value

A two-dimensional array can be understood as a table made of rows and columns.

01Why do we need two-dimensional arrays?

Some data naturally has rows and columns, such as a seating chart, a game board, or a table of values.

02How do you declare a two-dimensional array?

int a[2][3];

This declares 2 rows with 3 integers in each row.

03What does a[1][2] mean?

The first index selects the row, and the second selects the column. Since indexes start at 0, a[1][2] means the second row and third column.

Row and column indexes both start at 0.

04What is a two-dimensional array, really?

In C++:

int a[2][3];

You can think of a as an array of length 2, where each element is itself an array of 3 integers.

05How are elements arranged in memory?

An ordinary two-dimensional array is stored in contiguous row order:

a[0][0]→a[0][1]→a[0][2]→a[1][0]→...

This is commonly called row-major order.

06How do you traverse a two-dimensional array?

for (int row = 0; row < 2; row++) {
    for (int col = 0; col < 3; col++) {
        std::cout << a[row][col] << ' ';
    }
}

The outer loop controls the rows; the inner loop controls the columns.

07Can a two-dimensional array go out of bounds too?

Of course. For int a[2][3]:

  • Row indexes can only be 0 or 1.
  • Column indexes can only be 0, 1, or 2.

Both a[2][0] and a[0][3] are out of bounds.

What you have learned

  • A two-dimensional array is useful for representing rows and columns.
  • int a[2][3] means 2 rows, with 3 integers per row.
  • A two-dimensional array is an array of arrays.
  • An ordinary two-dimensional array is stored contiguously by row.
  • Nested loops are commonly used to traverse a two-dimensional array.

Next: What Is a String?

Your turn to try

For an array with 2 rows and 3 columns, is a[2][0] valid?

Ready? Open to see the explanation

No. The row index can only be 0 or 1. A valid column index cannot make an out-of-bounds row valid.