CodeBlanks Logo Icon CodeBlanks

Multidimensional arrays

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

Multidimensional arrays

A two-dimensional array in C holds data in matrix form. The declaration uses two pairs of brackets: first rows, then columns.

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

Here matrix is a 2-row × 3-column table. matrix[0][0] is 1, matrix[1][2] is 6. The first index selects the row, the second the column. Nested braces group rows.

Accessing matrix elements

You access a 2D array element with matrix[row][column]. Each index starts at 0.

int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};
printf("%d\n", matrix[0][2]);  // 3
printf("%d\n", matrix[1][0]);  // 4

Row 0, column 2 = 3. Row 1, column 0 = 4. To traverse matrices you use nested loops; the outer iterates rows, the inner columns.

Practice Print matrix elements

Write a C program. Declare int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};. Print the top-left and bottom-right elements with printf("%d %d\n", matrix[0][0], matrix[1][2]);. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare matrix, print two elements
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
    printf("%d %d\n", matrix[0][0], matrix[1][2]);
    return 0;
}

Expected output

1 6

Questions and answers

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

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

main.c
int matrix[2][3];
  • 6 Correct answer
  • 2
  • 3
  • 5

Explanation: Dimensions are multiplied.

2 Access the second element

Question
printf("%d
", matrix[0][____]);
Answer
printf("%d
", matrix[0][1]);

Explanation: matrix[0][1] is the second element of the first row.

3 Match the matrix concepts

Term Meaning
matrix[0][0] Top left
matrix[1][2] Bottom right
[2][3] 2 rows 3 cols
{1,2,3} One row

All lessons in Beginner