C Program to Add Two Matrices Using Multi-dimensional Arrays

1. Introduction

In the C programming language, multi-dimensional arrays are essentially arrays of arrays. A matrix is a perfect representation of a two-dimensional array. This tutorial will walk you through a C program that adds two matrices using multi-dimensional arrays.

2. Program Overview

1. Declare and initialize two two-dimensional arrays (matrices).

2. Use nested loops to traverse each element of the matrices.

3. Add corresponding elements of the two matrices and store the result in a third matrix.

4. Display the resultant matrix.

3. Code Program

#include <stdio.h>

int main() {
    int matrix1[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

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

    int result[3][3];
    int i, j;

    // Adding the two matrices and storing in result matrix
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            result[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }

    // Printing the resultant matrix
    printf("Resultant Matrix:\n");
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output:

Resultant Matrix:
10 10 10
10 10 10
10 10 10

4. Step By Step Explanation

1. We start by defining two matrices matrix1 and matrix2 of size 3x3 with some pre-defined values.

2. Another matrix named result is declared to store the sum of the two matrices.

3. Nested for loops are used to traverse the rows and columns of the matrices.

4. Inside the inner loop, the sum of elements from matrix1 and matrix2 at the current position (i, j) is computed and stored in the corresponding position of the result matrix.

5. The resultant matrix is then printed to display the sum of the two matrices.

Comments