Problem: In this programming example, we will learn to add two matrices in the C language.

Add two matrix

Steps to add two matrices in C:

  1. For loop from i=0 to i<row:
    1. For loop from j=0 to j<column:
      1. Assign summation result of the two matrix elements to the resultant matrix as res[i][j] = matrix1[i][j] + matrix2[i][j].
    2. End the j loop.
  2. End the i loop.

Here is the source code to add matrix in C:

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
 
int main()
{
  int row, column;

  //input order
  printf("Enter row and column order of the matrices\n");
  scanf("%d",&row);
  scanf("%d",&column);

  //define matrices
  int matrix1[MAX][MAX];
  int matrix2[MAX][MAX];

  //Input elements in 1st matrix
  printf("Enter %d elements in 1st matrix \n",row*column);
  for(int i=0; i<row; i++){
    for(int j=0; j<column; j++){
      scanf("%d", &matrix1[i][j]);
    }
  }

  //Input elements in 2nd matrix
  printf("Enter %d elements in 2nd matrix \n",row*column);
  for(int i=0; i<row; i++){
    for(int j=0; j<column; j++){
      scanf("%d", &matrix2[i][j]);
    }
  }

  //define resultant matrix
  int res[MAX][MAX]; 

  //Add Matrices
  for(int i=0; i<row; i++){
    for(int j=0; j<column; j++){
      res[i][j] = matrix1[i][j] + matrix2[i][j];
    }
  }
  
  //display resultant matrix 
  printf("--------Resultant Matrix------------\n");
  for(int i=0; i<row; i++){
    for(int j=0; j<column; j++){
      printf("%d \t", res[i][j]);
    }
    printf("\n");
  }

}

Output:

Enter row and column order of the matrices
2 2
Enter 4 elements in 1st matrix
1 2
2 1
Enter 4 elements in 2nd matrix
1 1
1 1
——–Resultant Matrix————
2 3
3 2


In the above program, we first input the order of the matrices and then define two matrices of the same size.

Next, we take input into both the matrices and then we add using the ‘for’ loop implementing the above described algorithm.

In this tutorial, we learned to add two matrices in the C programming language. If you have any doubt then do comment below.

Leave a Reply