Multidimensional arrays in C language
An array that contains other arrays is said to be multidimensional. These arrays are often set up with rows and columns in a rectangular or cube-like structure.
Using two pairs of square brackets and a comma to divide the number of entries in each dimension, we can declare a two-dimensional array.
Syntax of multidimensional array:
data_type array_name[size1][size2]...[sizeN];
- data_type is the data type of the array elements
- array_name is the name of the array.
- size1, size2, …, sizeN are the sizes of the array dimensions, separated by commas.
Here, matrix is the name of the array, and it can hold 3 rows and 3 columns. We can initialize the array elements during the declaration, like this:
int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
This initializes the array with the values 1 to 9 in a row-wise fashion. We can access the elements of the array using two indices, one for the row and another for the column. For example, matrix[0][0] refers to the element in the first row and first column, which is 1.
Similarly, we can declare and initialize a three-dimensional array like this:
int cube[2][3][4] = {
{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} },
{ {13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24} }
};
This creates a 2x3x4 array, with two “slices” of 3 rows and 4 columns each. We can access the elements of the array using three indices, one for each dimension. For example, cube[1][2][1] refers to the element in the second slice, third row, and second column, which is 22.
Example of multidimensional array:
#include <stdio.h>
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; // declaration and initialization
// accessing elements of the array using nested loops
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output:
1 2 3
4 5 6
In this example, we have declared and initialized a 2-dimensional array named matrix of size 2 rows by 3 columns. We then use nested loops to access and print each element of the array.
Another example of multidimensional array:
#include <stdio.h>
int main() {
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int arr[rows][cols];
// Taking input for array elements
printf("Enter the array elements: \n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &arr[i][j]);
}
}
// Displaying array elements
printf("The array elements are: \n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 2
Enter the number of columns: 3
Enter the array elements:
1 2 3
4 5 6
The array elements are:
1 2 3
4 5 6