Subtraction of Two Matrix in C
In this example, you will get and learn the example code of subtraction of two matrix in c program.
Here, first we will get size of matrix, Input elements in matrix 1 and matrix 2, calculate the subtract matrices, and print the matrix 3 as result.
Write a c program to subtract two 3×3 matrices
To subtract two 3×3 matrices in C, use nested loops to iterate through rows and columns, subtracting corresponding elements and storing the result in a new matrix.
For example:
k[i][j] = p[i][j] – q[i][j]
where i, j are the rows and columns
Example program to subtract two matrices are the following.
Subtraction of Two Matrix in C program
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 | //Subtract matrices in C #include<stdio.h> main() { int x[5][5],y[5][5],z[5][5],i,j; int r,c; //input size of matrix printf("\nEnter No of Rows & Columns (max : 5,5) :"); scanf("%d%d",&r,&c); //input matrix 1 elements printf("\nEnter Elements for 1st Matrix : "); for(i=0;i<r;i++) { for(j=0;j<c;j++) scanf("%d",&x[i][j]); } //input matrix 2 elements printf("\nEnter Elements for 2nd Matrix : "); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&y[i][j]); } } // Substraction of two Matrix for(i=0;i<r;i++) { for(j=0;j<c;j++) { z[i][j]=x[i][j]-y[i][j]; } } //print matrix After substraction printf("\nThe Elements After Substraction : \n\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf(" %d",z[i][j]); } printf("\n"); } return 0; } |
Output
Enter No of Rows & Columns (max : 5,5) :3
3
Enter Elements for 1st Matrix :
1 2 3
6 5 4
8 7 6
Enter Elements for 2nd Matrix :
2 3 4
2 3 1
4 3 2
The Elements After Substraction :
-1 -1 -1
4 2 3
4 4 4
Check out our other C programming Examples