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.
C Multi-Dimensional Array – Interview Questions
Q 1: What is a multi-dimensional array?
Ans: An array with more than one dimension, such as a 2D array.
Q 2: How do you declare a 2D array in C?
Ans: int arr[3][4];
Q 3: How is memory stored in a 2D array?
Ans: In row-major order.
Q 4: Where are multi-dimensional arrays used?
Ans: In matrices, tables, and grid-based problems.
Q 5: How do you access elements of a 2D array?
Ans: Using row and column indices, e.g., arr[i][j].
C Multi-Dimensional Array – Objective Questions (MCQs)
Q1. What is a two-dimensional array in C?
Q2. Which of the following declares a 2x3 integer array?
Q3. How do you access the element in the 2nd row and 3rd column of a 2D array arr?
Q4. What is the total number of elements in a 2x3x4 3D array?
Q5. Which statement is true about multi-dimensional arrays in C?