A multi-dimensional array in C is an array that contains other arrays as its elements. It is like an array of arrays. The most common type of multi-dimensional array is a 2D array, but you can also have 3D, 4D, etc.
In simple terms, a multi-dimensional array lets you store data in rows and columns (like a table or grid).
Syntax:
type arrayName[size1][size2];
Explanation:
- type: The data type of the elements in the array (e.g., int, float).
- size1: The number of rows.
- size2: The number of columns.
Example: 2D Array
#include <stdio.h>
int main() {
// Declare a 2D array (matrix) with 2 rows and 3 columns
int arr[2][3] = {{10, 20, 30}, {40, 50, 60}};
// Access and print elements of the 2D array
printf("Element at arr[0][0]: %d\n", arr[0][0]); // Output: 10
printf("Element at arr[0][1]: %d\n", arr[0][1]); // Output: 20
printf("Element at arr[1][2]: %d\n", arr[1][0]); // Output: 40
// Loop through the 2D array to print all elements
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
}
}
return 0;
}
Output:
Element at arr[0][0]: 10
Element at arr[0][1]: 20
Element at arr[1][2]: 40
arr[0][0] = 10
arr[0][1] = 20
arr[0][2] = 30
arr[1][0] = 40
arr[1][1] = 50
arr[1][2] = 60
Element at arr[0][1]: 20
Element at arr[1][2]: 40
arr[0][0] = 10
arr[0][1] = 20
arr[0][2] = 30
arr[1][0] = 40
arr[1][1] = 50
arr[1][2] = 60
Explanation:
- int arr[2][3]: This declares a 2D array with 2 rows and 3 columns.
- { {1, 2, 3}, {4, 5, 6} }: Initializes the array with values. The first row is {1, 2, 3}, and the second row is {4, 5, 6}.
- We can access elements like arr[0][0] (first row, first column), arr[1][2] (second row, third column), etc.