CodeBlanks Logo Icon CodeBlanks

Multidimensional arrays

Learn multidimensional arrays as matrices with int[][].

Multidimensional arrays

To hold data with more than one dimension you use a multidimensional array. The most common example is a 2D matrix: int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};.

The first dimension is the row count, the second the column count. matrix[i][j] gives the element at row i, column j. For example matrix[1][0] is the first element of the second row. You can picture the matrix as a grid.

Walking a matrix

To walk every element of a matrix you use two nested for loops. The outer loop covers rows, the inner covers columns: for (int i = 0; i < 2; i++) for (int j = 0; j < 3; j++) std::cout << matrix[i][j];.

This is called a nested loop. For each row, all columns are walked, then the outer loop moves to the next row. To print the matrix row by row you can add a std::endl at the end of each row.

Practice Print a matrix element

Declare a 2x3 matrix as int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; and print the first element of the second row with std::cout << matrix[1][0];. The output must be 4.

Starter code

main.cpp
#include <iostream>

int main() {
    // Declare a 2x3 matrix and print matrix[1][0]
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
    std::cout << matrix[1][0] << std::endl;
    return 0;
}

Expected output

4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many elements does int m[2][3] hold?

main.cpp
int m[2][3];
  • 6 Correct answer
  • 2
  • 3
  • 5

Explanation: 2 rows × 3 columns = 6 elements.

2 Write the multidimensional access

Question
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
std::cout << ____;
Answer
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
std::cout << matrix[1][2];

Explanation: matrix[1][2] is the third element of the second row (6).

3 Match each matrix concept to its meaning

Term Meaning
matrix[0] First row
matrix[i][j] Row i, column j
[2][3] 2 rows 3 columns
{{1,2,3},{4,5,6}} 2x3 initial values

All lessons in Beginner