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
#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
- Create a 3 by 3 grid and print it in matrix form.
- Calculate the sum of all elements using nested loops.
- Calculate the sum of each row separately.
- Print the main diagonal of a square matrix.
Practice solutions
Show worked solutions
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'; }- Initialize
int total = 0;, visit everygrid[row][col]with the two loops, and add each value tototal. For the sample grid the sum is 45. - 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.
- For a square matrix, print
grid[i][i]forifrom 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.