Write a C program to read elements in two matrices and find the difference of two matrices. Program to subtract two matrices in C.

If matrix 1:

1 2 3

4 5 6

7 8 9

And matrix 2:

9 8 7

6 5 4

3 2 1

Difference of both matrices =

-8 -6 -4

-2 0 2

4 6 8

Matrix subtraction is done element wise (entry wise) i.e. Difference of two matrices

(

Happy coding ;)

**Example:**If matrix 1:

1 2 3

4 5 6

7 8 9

And matrix 2:

9 8 7

6 5 4

3 2 1

Difference of both matrices =

-8 -6 -4

-2 0 2

4 6 8

### Required knowledge:

Basic C programming, For loop, Array, Matrix#### Matrix Subtraction:

Matrix subtraction is a simple and easy process. Elements of two matrices can only be subtracted if and only if both matrices are of same size.Matrix subtraction is done element wise (entry wise) i.e. Difference of two matrices

**A**and**B**of size mXn is defined by(

**A**-**B**) =**A**_{ij}-**B**_{ij}(Where 1 ≤ i ≤ m and 1 ≤ j ≤ n )### Program:

/** * C program to find difference of two matrices of size 3x3 */ #include <stdio.h> int main() { int A[3][3], B[3][3], C[3][3]; int row, col; /* * Reads elements in first matrix */ printf("Enter elements in matrix A of size 3x3: \n"); for(row=0; row<3; row++) { for(col=0; col<3; col++) { scanf("%d", &A[row][col]); } } /* * Reads elements in second matrix */ printf("\nEnter elements in matrix B of size 3x3: \n"); for(row=0; row<3; row++) { for(col=0; col<3; col++) { scanf("%d", &B[row][col]); } } /* * Subtracts both matrices and stores the result in matrix C */ for(row=0; row<3; row++) { for(col=0; col<3; col++) { C[row][col] = A[row][col] - B[row][col]; } } /* * Prints the difference of both matrices A and B */ printf("\nDifference of two matrices A-B = \n"); for(row=0; row<3; row++) { for(col=0; col<3; col++) { printf("%d ", C[row][col]); } printf("\n"); } return 0; }

Output

Enter elements in matrix A of size 3x3:

1 2 3

4 5 6

7 8 9

Enter elements in matrix B of size 3x3:

9 8 7

6 5 4

3 2 1

Difference of both matrices A-B =

-8 -6 -4

-2 0 2

4 6 8

1 2 3

4 5 6

7 8 9

Enter elements in matrix B of size 3x3:

9 8 7

6 5 4

3 2 1

Difference of both matrices A-B =

-8 -6 -4

-2 0 2

4 6 8

Happy coding ;)

### You may also like

- Array and Matrix programming exercises index.
- C program to add two matrices.
- C program to multiply two matrices.
- C program to perform Scalar matrix multiplication.
- C program to find transpose of a matrix.
- C program to find determinant of a matrix.
- C program to check Identity matrix.
- C program to find sum of all array elements.
- C program to find maximum and minimum elements in an array.
- C program to count total number of duplicate elements in an array.
- C program to count total number of negative elements in an array.
- C program to count frequency of each element in an array.

< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)