Here's a C program to subtract the given two matrices with proper explanation and output. This program uses Multidimensional Arrays, Nested Loops and For Loops.
# include <stdio.h> # include <conio.h> void main() { int mata[10][10], matb[10][10], matc[10][10] ; int i, j, row, col ; clrscr() ; printf("Enter the order of the matrix : ") ; scanf("%d %d", &row, &col) ; printf("\nEnter the elements of first matrix : \n\n") ; for(i = 0 ; i < row ; i++) for(j = 0 ; j < col ; j++) scanf("%d", &mata[i][j]) ; printf("\nEnter the elements of second matrix : \n\n") ; for(i = 0 ; i < row ; i++) for(j = 0 ; j < col ; j++) scanf("%d", &matb[i][j]) ; for(i = 0 ; i < row ; i++) for(j = 0 ; j < col ; j++) matc[i][j] = mata[i][j] - matb[i][j] ; printf("\nThe resultant matrix is : \n\n") ; for(i = 0 ; i < row ; i++) { for(j = 0 ; j < col ; j++) { printf("%d \t", matc[i][j]) ; } printf("\n") ; } getch() ; }
Output of above program
Enter the order of the matrix : 3 3
Enter the elements of first matrix :
5 10 15
20 25 30
35 40 45
Enter the elements of second matrix :
2 4 6
8 10 12
14 16 18
The resultant matrix is :
3 6 9
12 15 18
21 24 27
Explanation of above program
In this program, we have three square matrices mata, matb and matc all of maximum size 10 x
10. The matrices mata and matb are the two matrices whose difference we wish to calculate and matrix matc contains the difference of mata and matb. The variables i and j are the loop variables that corresponds to
the row and column of the matrix respectively. The variables row and col contain the row and column i.e. the order of the matrix.
First,
the program prompts the user to enter the order of the matrix. Since
two matrices can be subtracted only when they are of the same order, so, we
need to enter the order only once. After getting the order of the
matrices using first two Nested For Loops the program populates the matrices mata and matb.
The difference of two matrices mata and matb is calculated using the third nested for loop and then stored in the matrix matc. Using the fourth and last nested for loop, the values in the matrix matc i.e. the difference of the given matrices is printed on the screen.
Also look at: C Program to Add the Given Two Matrices