C Program to substract two matrix.
Objective
Write a C program to subtract two 2D Matrices.
Algorithm / Approach
- Declare three 3x3 matrices.
- Read the data for the first two matrices using nested loops.
- Calculate the difference by subtracting matching coordinates:
m3[i][j] = m1[i][j] - m2[i][j]. - Print the resulting difference matrix.
main.c
#include<stdio.h>
int main( ) {
int r=3, c=3, i, j ;
int m1[3][3], m2[3][3],m3[3][3];
printf("Enter elements of mat1: ");
for (i = 0; i < r; i++){
for (j = 0; j < c; j++){
scanf("%d", &m1[i][j]);
}
}
printf("Enter elements of mat2: ");
for (i = 0; i < r; i++){
for (j = 0 ; j < c; j++){
scanf("%d", &m2[i][j]);
}
}
printf("Difference of Matrix :\n");
for (i = 0; i < r; i++) {
for (j = 0 ; j < c; j++) {
m3[i][j] = m1[i][j]-m2[i][j];
printf("%d ", m3[i][j]);
}
printf("\n");
}
return 0;
}
Expected Output
Enter elements of mat1 : 6 5 3 3 4 5 6 5 3 Enter elements of mat2: 1 2 3 2 3 4 1 5 4 Difference of Matrix : 5 3 0 1 1 1 5 0 -1
Explanation of the Program
- Matrix subtraction follows the exact same logic as matrix addition.
- Remember that for matrix addition and subtraction to be mathematically valid, both matrices must have the exact same dimensions (e.g., both must be 3x3 or 2x4).
Complexity
Time Complexity
O(r * c)
Space Complexity
O(r * c)