Matrix Addition in C

Problem Statement: Given two matrices add the value of the two matrices and print the resultant matrix.

Example 1:
Input: mat1[][] = 1 1 1   mat2= 2 2 2
                  1 1 1         2 2 2
                  1 1 1         2 2 2
Output: 3 3 3
        3 3 3
        3 3 3

Example 2:
Input: mat1[][] = 2 2 2   mat2= 2 2 2
                  2 2 2         2 2 2
                  2 2 2         2 2 2
Output: 4 4 4
        4 4 4
        4 4 4

DisclaimerDon’t jump directly to the solution, try it out yourself first.

It’s as simple as it appears to be. Two add two matrix, it is as simple as adding two numbers. However, here instead of adding just two numbers you need to perform addition of one element of first matrix to one element for second matrix for all elements present in the matrices.

However, in order to perform addition operation on two matrices, both matrix needs to be of same dimension. That is, both matrices should have equal number of rows and columns.

Approach:

  • We are given two matrices mat1, mat2
  • Declare a matrix called sum in which the resultant sum will be stored
  • Run a nested loop starting from i =0 to n, where n is the number of rows and j = 0 to m where m is the number of columns.
  • Now in each step sum[i][j] = mat1[i][j] + mat2[i][j]
  • Print the matrix sum.

Code:

C Programs

#include <stdio.h>
int main() {
  int sum[3][3], i, j;
  int mat1[3][3]={{1,1,1},{1,1,1},{1,1,1}};
  int mat2[3][3]={{2,2,2},{2,2,2},{2,2,2}};
  

  printf("Elements of first matrix: \n");
  for (i = 0; i < 3; ++i){
    for (j = 0; j < 3; ++j) {
      printf("%d   ", mat1[i][j]);
    }
        printf("\n");
      }
    

  printf("Elements of second matrices: \n");
  for (i = 0; i < 3; ++i){
    for (j = 0; j < 3; ++j) {
      printf("%d   ", mat2[i][j]);
    }
        printf("\n");
      }
    

  // adding two matrices
  for (i = 0; i < 3; ++i)
    for (j = 0; j < 3; ++j) {
      sum[i][j] = mat1[i][j] + mat2[i][j];
    }

  // printing the result
  printf("\nSum of two matrices: \n");
  for (i = 0; i < 3; ++i){
    for (j = 0; j < 3; ++j) {
      printf("%d   ", sum[i][j]);
    }
        printf("\n");
      }
    

  return 0;
}

Output:

Elements of first matrix:
1 1 1
1 1 1
1 1 1
Elements of second matrices:
2 2 2
2 2 2
2 2 2

Sum of two matrices:
3 3 3
3 3 3
3 3 3

Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article