OverIQ.com

C Program to add two Matrices

Last updated on September 23, 2020


The following is a C program which asks the user to input two matrices and then adds them.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/******************************************
* Program to add two add matrices
******************************************/

#include<stdio.h> // include stdio.h
#define ROW 2
#define COL 3

int main()
{
    int i, j, arr1[ROW][COL], arr2[ROW][COL];

    printf("Enter first matrix: \n");

    for(i = 0; i < ROW; i++)
    {
        for(j = 0; j < COL; j++)
        {
            scanf("%d", &arr1[i][j]);
        }        
    }

    printf("\nEnter second matrix: \n");

    for(i = 0; i < ROW; i++)
    {
        for(j = 0; j < COL; j++)
        {         
            scanf("%d", &arr2[i][j]);
        }                
    }

    printf("\narr1 + arr2 = \n");

    // add two matrices
    for(i = 0; i < ROW; i++)
    {
        for(j = 0; j < COL; j++)
        {
            printf("%5d ", arr1[i][j] + arr2[i][j]);            
        }        
        printf("\n");
    }       

    // signal to operating system everything works fine
    return 0;
}

Try it now

Expected Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Enter first matrix: 
1 2 3
4 5 6

Enter second matrix: 
2 4 6
8 10 12

arr1 + arr2 = 
    3     6     9 
   12    15    18

How it works #

To add or subtract matrices we simply add or subtract corresponding entries in each matrix respectively.

\[
\left(\begin{array}{cc}A_{11} & A_{12} \\A_{21} &A_{22}\end{array}\right) + \left(\begin{array}{cc}B_{11} & B_{12}\\B_{21} &B_{22}\end{array}\right) = \left(\begin{array}{cc}A_{11}+B_{11} & A_{12}+B_{12}\\A_{21}+B_{21} &A_{22}+B_{22}\end{array}\right)
\]

Note that matrix addition or subtraction is only possible when both the matrices are of same size.

Here is how the above program works:

  • The first for loop in lines 15-22, asks the user to enter the first matrix.
  • The second for loop in lines 26-33, asks the user to enter the second matrix.
  • The third for loop (lines 38-45) displays the resultant matrix by adding add the corresponding entries in each matrix.

Recommended Reading: