All lessons

6. Arrays

2D arrays

0 of 5 activities0%

Reading 1

A table of values

Open

A 2D array is an array of arrays: int grid[3][4] has 3 rows and 4 columns.

Access with grid[r][c]. Nested loops usually walk rows in the outer loop and columns in the inner loop.

Think “row, then column” when you read grid[r][c].

int grid[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};
cout << grid[1][2] << endl;  // 6

for (int r = 0; r < 2; r++) {
    for (int c = 0; c < 3; c++) {
        cout << grid[r][c] << " ";
    }
    cout << endl;
}

Check 2

Indexing order

Open

In grid[r][c], what does r usually mean?

Fill in 3

Access

Open

To read row 0, column 2 of grid you write grid

Try it 4

Print a matrix

Open

Change a value and reprint.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Sum a 2x2

Open

Read four integers into a 2x2 array (row by row). Print the sum of all four.

main.cpp
Loading editor…