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).
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 |
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.
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. |
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):
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 |
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:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j; |