Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

Multidimensional Arrays

Multidimensional Arrays

In the preceding chapter, you acquired knowledge about arrays, also referred to as single-dimensional arrays. These are indispensable and frequently utilized in C programming. Nonetheless, to accommodate data in a tabular format resembling a table with rows and columns, acquainting yourself with multidimensional arrays is essential.

A multidimensional array fundamentally comprises arrays nested within each other.

Arrays can possess numerous dimensions. Throughout this chapter, we will primarily focus on introducing the most prevalent type: two-dimensional arrays (2D).

Two-Dimensional Arrays

A two-dimensional array is commonly referred to as a matrix, which represents a table with rows and columns.

To generate a two-dimensional array of integers, consider the following example:

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

The first dimension denotes the number of rows [2], whereas the second dimension signifies the number of columns [3].

The values are arranged in row-major order and can be envisioned as follows:

 

COLUMN 0

COLUMN 1

COLUMN 2

ROW 0

1

4

2

ROW 1

3

6

8

Access the Elements of a 2D Array

To retrieve an element from a two-dimensional array, you need to specify both the row and column indices.

This line accesses the value of the element located in the first row (index 0) and third column (index 2) of the matrix array.

Example

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

printf(“%d”, matrix[0][2]);  // Outputs 2 

 

Keep in mind that array indexes begin with 0: [0] denotes the first element, [1] represents the second element, and so forth.

Change Elements in a 2D Array

To modify the value of an element, specify the index number of the element in each dimension:

The subsequent example demonstrates altering the value of the element in the first row (0) and first column (0):

Example

int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf(“%d”, matrix[0][0]);  // Now outputs 9 instead of 1 

Loop Through a 2D Array

To iterate through a multidimensional array, you require one loop for each dimension of the array.

The subsequent example prints all elements in the matrix array:

Example

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

int i, j;
for (i = 0; i < 2; i++) {
  for (j = 0; j < 3; j++) {
    printf(“%d\n”, matrix[i][j]);
  }