C Program to add two Matrices

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

Expected Output:

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:

Leave a Comment

%d bloggers like this: