Exploring Multi-dimensional Arrays in C: Mastering Arrays and Strings

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 [].

int matrix[3][3]; // Declares a 3x3 integer matrix

Initializing Multi-dimensional Arrays

You can initialize a multi-dimensional array at the time of declaration using nested curly braces {} to represent each dimension.

int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

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:

int element = matrix[1][2]; // Accesses the element at row 1, column 2 (value 6)

Example: Matrix Multiplication

Let’s see a practical example of matrix multiplication using multi-dimensional arrays.

#include <stdio.h>
int main() {
    int matrix1[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };
    int matrix2[3][2] = {
        {7, 8},
        {9, 10},
        {11, 12}
    };
    int result[2][2] = {0}; // Initialize the result matrix with zeros
    // Matrix multiplication
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 3; k++) {
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }
    // Display the result
    printf("Resultant Matrix:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }
    return 0;
}

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:

Resultant Matrix:
58  64 
139 154 
Author: user