Add Two Matrices Using Multi-dimensional Arrays in C

Exercise:

Write a C Program to add two matrices using multi-dimensional arrays.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    int row, col, a[100][100], b[100][100], sum[100][100], i, j;
    printf("Enter the number of rows (between 1 and 100): ");
    scanf("%d", &row);
    printf("Enter the number of columns (between 1 and 100): ");
    scanf("%d", &col);
    printf("\nEnter elements of 1st matrix:\n");
    for (i = 0; i < row; ++i) {
        for (j = 0; j < col; ++j) {
            printf("Enter element a%d%d: ", i + 1, j + 1);
            scanf("%d", &a[i][j]);
         }
    }

    printf("Enter elements of 2nd matrix:\n");
    for (i = 0; i < row; ++i) {
        for (j = 0; j < col; ++j) {
            printf("Enter element a%d%d: ", i + 1, j + 1);
            scanf("%d", &b[i][j]);
        }
    }

    for (i = 0; i < row; ++i) {
        for (j = 0; j < col; ++j) {
            sum[i][j] = a[i][j] + b[i][j];
        }
    }

    // Printing Result
    printf("\nSum of two matrices: \n");
    for (i = 0; i < row; ++i) {
        for (j = 0; j < col; ++j) {
            printf("%d   ", sum[i][j]);
            if (j == col - 1) {
                printf("\n\n");
            }
        }
    }
    return 0;
}
Click Here to View the Output!
 Enter the number of rows (between 1 and 100): 2
 Enter the number of columns (between 1 and 100): 2
 Enter elements of 1st matrix:
 Enter element a11: 1
 Enter element a12: 2
 Enter element a21: 3
 Enter element a22: 4
 Enter elements of 2nd matrix:
 Enter element a11: 5
 Enter element a12: 6
 Enter element a21: 7
 Enter element a22: 8
 Sum of two matrices: 
 6   8
 10   12 
Click Here to View the Explanation!
  • This program is used to add two matrices by using multidimensional arrays.
  • In main(), three multidimensional arrays a, b and sum are declared; each with a capacity of 100 rows and 100 columns.
  • The program requests the user to enter the number of rows and columns and stores the values in the variables row and col using the scanf() function.
  • The program then requests the user to enter elements of the first matrix (a[i][j]) and second matrix (b[i][j]) by using nested for loops that iterate between the multidimensional arrays in the manner of first row and all its columns, second row and all its columns and so on.
  • The two matrices are then added a[i][j] + b[i][j] by using the same nested for loops and their result is stored in another matrix sum[i][j].
  • The sum is then finally printed row-wise. And once the inner loop reaches to the (c – 1)th value, the loop exits and the outer loop starts executing again for the second row.
%d bloggers like this: