C program to find sum and subtraction of two matrices

Here, we are going to learn how to find the sum and subtraction of two matrices in C language.

Problem statement

Given two matrices a and b, write a C program to find its sum and subtraction.

C program to find sum and subtraction of two matrices

Below is the C program to find the sum and subtraction of two matrices:

```#include <stdio.h>

#define MAXROW 10
#define MAXCOL 10

/*User Define Function to Read Matrix*/
void readMatrix(int m[][MAXCOL], int row, int col) {
int i, j;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("Enter element [%d,%d] : ", i + 1, j + 1);
scanf("%d", &m[i][j]);
}
}
}

/*User Define Function to Read Matrix*/
void printMatrix(int m[][MAXCOL], int row, int col) {
int i, j;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d\t", m[i][j]);
}
printf("\n");
}
}

int main() {
int a[MAXROW][MAXCOL], b[MAXROW][MAXCOL], result[MAXROW][MAXCOL];
int i, j, r1, c1, r2, c2;

printf("Enter number of Rows of matrix a: ");
scanf("%d", &r1);
printf("Enter number of Cols of matrix a: ");
scanf("%d", &c1);

printf("\nEnter elements of matrix a: \n");

printf("Enter number of Rows of matrix b: ");
scanf("%d", &r2);
printf("Enter number of Cols of matrix b: ");
scanf("%d", &c2);

printf("\nEnter elements of matrix b: \n");

/*sum and sub of Matrices*/
if (r1 == r2 && c1 == c2) {
/*Adding two matrices a and b, and result storing in matrix result*/
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}

/*print matrix*/
printMatrix(result, r1, c1);

/*Subtracting two matrices a and b, and result storing in matrix result*/
for (i = 0; i < r1; i++) {
for (j = 0; j < c1; j++) {
result[i][j] = a[i][j] - b[i][j];
}
}

/*print matrix*/
printf("\nMatrix after subtracting (result matrix):\n");
printMatrix(result, r1, c1);

} else {
printf("\nMatrix can not be added, Number of Rows & Cols are Different");
}
return 0;
}
```

Output

```Enter number of Rows of matrix a: 3
Enter number of Cols of matrix a: 3

Enter elements of matrix a:
Enter element [1,1] : 11
Enter element [1,2] : 22
Enter element [1,3] : 33
Enter element [2,1] : 44
Enter element [2,2] : 55
Enter element [2,3] : 66
Enter element [3,1] : 77
Enter element [3,2] : 88
Enter element [3,3] : 99

Enter number of Rows of matrix b: 3
Enter number of Cols of matrix b: 3

Enter elements of matrix b:
Enter element [1,1] : 1
Enter element [1,2] : 2
Enter element [1,3] : 3
Enter element [2,1] : 4
Enter element [2,2] : 5
Enter element [2,3] : 6
Enter element [3,1] : 7
Enter element [3,2] : 8
Enter element [3,3] : 9

12	24	36
48	60	72
84	96	108

Matrix after subtracting (result matrix):
10	20	30
40	50	60
70	80	90
```