Contents
Multi dimensional Array
In the previous section, you learned about arrays, also known as one-dimensional arrays. These are great and I will be using them a lot when programming in C. However, if you want to store data in a tabular format (like a table with rows and columns), you need to know more about arrays.
Multidimensional arrays are basically arrays.
Arrays can have any number of dimensions. In this section we will look at the most; two-dimensional arrays (2D).
Two Dimensional Array
A two-dimensional array can be defined as an array of arrays. Two-dimensional arrays are organized as matrices that can be represented as collections of rows and columns. However, two-dimensional arrays are created using data structures similar to relational databases. It can hold many files at once, which can be sent to any project when needed.
Declaration of (2 –D) Array
Here’s the syntax for declaring a two-dimensional array:
data_type array_name[rows][columns];
Where:
data_type is the type of data that the array will store (e.g., int, char, float, etc.).
array_name is the name of the array.
rows is the number of rows in the array.
columns is the number of columns in the array.
Initialization of 2D Array in C
In a one-dimensional array, we do not need to specify the size of the array if dispatch and initialization occur simultaneously. But this doesn’t work for 2D arrays. We need to define at least the second element of the array. Two-dimensional arrays are declared and defined as follows.
- int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example
#include <stdio.h>
int main() {
// Declaration and initialization of a 2D array
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Accessing and printing elements of the array
printf(“Elements of the 2D array:\n”);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf(“%d “, matrix[i][j]);
}
printf(“\n”);
}
return 0;
}
Output
Elements of the 2D array:
1 2 3 4
5 6 7 8
9 10 11 12
Here’s an example of storing elements in a 2D array (matrix) and printing it in C
#include <stdio.h>
int main() {
// Declaration of a 2D array (matrix)
int matrix[3][3];
// Storing elements in the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf(“Enter element at position [%d][%d]: “, i, j);
scanf(“%d”, &matrix[i][j]);
}
}
// Printing the matrix
printf(“\nThe matrix is:\n”);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf(“%d “, matrix[i][j]);
}
printf(“\n”); // Move to the next row
}
return 0;
}
Output
Enter element at position [0][0]: 1
Enter element at position [0][1]: 2
Enter element at position [0][2]: 3
Enter element at position [1][0]: 4
Enter element at position [1][1]: 5
Enter element at position [1][2]: 6
Enter element at position [2][0]: 7
Enter element at position [2][1]: 8
Enter element at position [2][2]: 9
The matrix is:
1 2 3
4 5 6
7 8 9