C++ PROGRAMMING ยท 14 MIN STUDY

Multidimensional arrays and nested loops

Represent tables with two-dimensional arrays and traverse rows and columns using nested loops.

Learning objectives

  • Declare and initialize a two-dimensional built-in array.
  • Use row and column indexes correctly.
  • Traverse a matrix with nested loops.
  • Understand row-major storage at a high level.

Prerequisites: be comfortable with one-dimensional arrays, zero-based indexing, and nested loops. Review Arrays and Nested loops first.

Think in rows and columns

A two-dimensional array is useful for grid-like data such as a board, table, or matrix. The first index selects a row; the second selects a column.

int grid[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

// Visual layout:
// row 0: [1] [2] [3]
// row 1: [4] [5] [6]

The comments show the same values as a grid; they are explanatory labels, not extra C++ statements. The array declaration itself is valid C++ and can be copied into a function or source file.

The declaration means two rows and three columns. Valid row indexes are 0 and 1; valid column indexes are 0, 1, and 2.

Traverse with nested loops

C++17
#include <iostream>

int main() {
    int grid[2][3]{{1, 2, 3}, {4, 5, 6}};
    for (int row = 0; row < 2; ++row) {
        for (int col = 0; col < 3; ++col) {
            std::cout << grid[row][col] << ' ';
        }
        std::cout << '\n';
    }
}

The outer loop chooses a row. For each row, the inner loop visits every column. The inner loop completes before the outer loop advances to the next row.

Row-major layout

Built-in multidimensional arrays in C++ are arrays of arrays. Elements of each row are contiguous, and rows appear in order. This is called row-major layout. Traversing the last index in the inner loop follows contiguous elements and is usually cache-friendly.

Common mistakes

  • Using the number of rows as the column limit.
  • Starting indexes at 1 rather than 0.
  • Accessing grid[2][0] in a two-row array.
  • Swapping row and column indexes.

Practice

  1. Create a 3 by 3 grid and print it in matrix form.
  2. Calculate the sum of all elements using nested loops.
  3. Calculate the sum of each row separately.
  4. Print the main diagonal of a square matrix.

Practice solutions

Show worked solutions
  1. int grid[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    for (int row = 0; row < 3; ++row) {
        for (int col = 0; col < 3; ++col)
            std::cout << grid[row][col] << ' ';
        std::cout << '\n';
    }
  2. Initialize int total = 0;, visit every grid[row][col] with the two loops, and add each value to total. For the sample grid the sum is 45.
  3. For each row, initialize a row sum to zero, add its three elements, then print the row sum. The sample row sums are 6, 15, and 24.
  4. For a square matrix, print grid[i][i] for i from zero to two. The sample diagonal is 1, 5, 9.

Check your understanding

For int a[4][5], what are the valid indexes?

Answer: First index 0 through 3; second index 0 through 4.

Summary

Two-dimensional arrays represent rows and columns. Use an outer loop for rows and an inner loop for columns, and check each index against its own dimension.

References