You are here

Matrix addition in C

Matrix addition in C: C program to add two matrices, i.e., compute the sum of two matrices and then print it. Firstly a user will be asked to enter the order of matrix (number of rows and columns) and then two matrices. For example, if a user input order as 2, 2, i.e., two rows and two columns and matrices as
First matrix:
1 2
3 4
Second matrix:
4 5
-1 5
then the output of the program (Summation of the two matrices) is:
5 7
2 9

Matrices are frequently used in programming to represent graph data structure, in solving equations and in many other ways.

Addition of two matrix in C

C program for matrix addition:

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int m, n, c, d, first[10][10], second[10][10], sum[10][10];
  6.  
  7.    printf("Enter the number of rows and columns of matrix\n");
  8.    scanf("%d%d", &m, &n);
  9.    printf("Enter the elements of first matrix\n");
  10.  
  11.    for (c = 0; c < m; c++)
  12.       for (d = 0; d < n; d++)
  13.          scanf("%d", &first[c][d]);
  14.  
  15.    printf("Enter the elements of second matrix\n");
  16.  
  17.    for (c = 0; c < m; c++)
  18.       for (d = 0 ; d < n; d++)
  19.          scanf("%d", &second[c][d]);
  20.    
  21.    printf("Sum of entered matrices:-\n");
  22.    
  23.    for (c = 0; c < m; c++) {
  24.       for (d = 0 ; d < n; d++) {
  25.          sum[c][d] = first[c][d] + second[c][d];
  26.          printf("%d\t", sum[c][d]);
  27.       }
  28.       printf("\n");
  29.    }
  30.  
  31.    return 0;
  32. }

Output of matrix addition C program:
Matrix addition in C program output

Download Add Matrix program.

Similarly, we can create a program to subtract two matrices. You can also create a function to perform addition of two matrices.