#include<stdio.h> #include<conio.h> void main() { int i,j,a[10][10],b[10][10],c[10][10],m1,n1,m2,n2; /* m - Number of rows n - Number of Columns */ clrscr(); printf("Enter the number of Rows of Mat1 : "); scanf ("%d",&m1); printf("Enter the number of Columns of Mat1 : "); scanf ("%d",&n1); /* Accept the Elements in m x n Matrix */ for( i = 0 ; i < m1 ; i++ ) for( j = 0 ; j < n1 ; j++ ) { printf("Enter the Element a[%d][%d] : ",i,j); scanf("%d",&a[i][j]); } // ------------------------------------------ printf("nEnter the number of Rows of Mat2 : "); scanf ("%d",&m2); printf("nEnter the number of Columns of Mat2 : "); scanf ("%d",&n2); /* Before accepting the Elements Check if no of rows and columns of both matrices is equal */ if ( m1 != m2 || n1 != n2 ) { printf("nOrder of two matrices is not same "); exit(0); } // ------ Terminate Program if Orders are unequal // ------ exit(0) : 0 for normal Termination /* Accept the Elements in m x n Matrix */ for( i = 0 ; i < m2 ; i++ ) for( j = 0 ; j < n2 ; j++ ) { printf("Enter the Element b[%d][%d] : ",i,j); scanf("%d",&b[i][j]); } // ------------------------------------------ /* Subtraction of two matrices */ for( i = 0 ; i < m1 ; i++ ) for( j = 0 ; j < n1 ; j++ ) { c[i][j] = a[i][j] - b[i][j] ; } /* Print out the Resultant Matrix */ printf("nThe Subtraction of two Matrices is : n"); for( i = 0 ; i < m1 ; i++ ) { for( j = 0 ; j < n1 ; j++ ) { printf("%dt",c[i][j]); } printf("n"); } getch(); }
Output :
Enter the number of Rows of Mat1 : 3 Enter the number of Columns of Mat1 : 3 Enter the Element a[0][0] : 2 Enter the Element a[0][1] : 4 Enter the Element a[0][2] : 6 Enter the Element a[1][0] : 4 Enter the Element a[1][1] : 2 Enter the Element a[1][2] : 2 Enter the Element a[2][0] : 2 Enter the Element a[2][1] : 4 Enter the Element a[2][2] : 2 Enter the number of Rows of Mat2 : 3 Enter the number of Columns of Mat2 : 3 Enter the Element b[0][0] : 1 Enter the Element b[0][1] : 2 Enter the Element b[0][2] : 3 Enter the Element b[1][0] : 2 Enter the Element b[1][1] : 1 Enter the Element b[1][2] : 1 Enter the Element b[2][0] : 1 Enter the Element b[2][1] : 2 Enter the Element b[2][2] : 1 The Subtraction of two Matrices is : 1 2 3 2 1 1 1 2 1
Note : 2-D array needs two nested for loops
Keep in mind :
Keep in mind :
- One Matrix can be subtracted with another only if the order of both matrices is Equal
- No of rows of MAT-1 = No of rows of MAT-2
- No of col of MAT-1 = No of col of MAT-2
- During subtraction b[0][0] is subtracted from a[0][0] and result is stored in c[0][0]
We required two ‘for loops’ (nested) for following Perpose :
- Accepting Matrix
- Displaying Matrix
- Manipulating Matrix
- Performing Different Operations on Matrix
No comments:
Post a Comment