Multi-dimensional arrays are an essential part of C programming, allowing you to work with tables, matrices, and more complex data structures. In this article, we will explore multi-dimensional arrays in C, covering their declaration, initialization, and practical examples with code and output. Multi-dimensional arrays are powerful data structures in C that enable you to work with structured data efficiently.
What Are Multi-dimensional Arrays?
A multi-dimensional array in C is an array of arrays. It allows you to store data in a grid or matrix-like structure. Multi-dimensional arrays can have two or more dimensions, making them suitable for tasks where data needs to be organized in rows and columns.
Declaring Multi-dimensional Arrays
To declare a multi-dimensional array, you specify the data type of its elements, followed by the array’s name and the dimensions enclosed in square brackets []
.
Initializing Multi-dimensional Arrays
You can initialize a multi-dimensional array at the time of declaration using nested curly braces {}
to represent each dimension.
Accessing Elements in Multi-dimensional Arrays
To access an element in a multi-dimensional array, you use multiple indices. For example, to access the element in the second row and third column of the matrix:
Example: Matrix Multiplication
Let’s see a practical example of matrix multiplication using multi-dimensional arrays.
In this example, we declare and initialize two matrices, matrix1
and matrix2
. We then perform matrix multiplication using nested loops and store the result in the result
matrix. Finally, we display the resultant matrix. The output of this program will be: