Matrix Subtraction using Arrays in C
Matrix subtraction in C is performed by subtracting corresponding elements of two matrices and storing the result in a third matrix. This is achieved using nested loops to iterate through the rows and columns of the matrices.
Examples of Matrix Subtraction
1. Subtracting Two 2×2 Matrices
In this example, we will subtract two 2×2 matrices and store the result in another 2×2 matrix.
main.c
</>
Copy
#include <stdio.h>
int main() {
int A[2][2] = {{5, 7}, {9, 11}};
int B[2][2] = {{1, 2}, {3, 4}};
int result[2][2];
// Subtract matrices A and B
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = A[i][j] - B[i][j];
}
}
// Print the result matrix
printf("Resultant Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Explanation:
- We declare two 2×2 matrices
A
andB
, and a third matrixresult
to store the difference. - Using nested
for
loops, we iterate through each row and column. - Inside the loop, we subtract corresponding elements of
A
andB
and store them inresult
. - Another nested loop prints the resulting matrix.
Output:
Resultant Matrix:
4 5
6 7
2. Subtracting Two 3×3 Matrices
In this example, we will subtract two 3×3 matrices and store the result in another 3×3 matrix.
main.c
</>
Copy
#include <stdio.h>
int main() {
int A[3][3] = {{8, 7, 6}, {5, 4, 3}, {2, 1, 0}};
int B[3][3] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}};
int result[3][3];
// Subtract matrices A and B
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = A[i][j] - B[i][j];
}
}
// Print the result matrix
printf("Resultant Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Explanation:
- We define two 3×3 matrices
A
andB
, and a result matrix. - Using nested loops, we iterate through all elements of the matrices.
- Each element of
B
is subtracted from the corresponding element ofA
and stored inresult
. - Finally, another nested loop prints the result matrix.
Output:
Resultant Matrix:
7 6 5
4 3 2
1 0 -1
Conclusion
In this tutorial, we learned how to perform matrix subtraction using arrays in C. We covered:
- Basic Matrix Subtraction: Using nested loops to subtract corresponding elements.
- Implementation with Different Matrix Sizes: Demonstrated with 2×2 and 3×3 matrices.
- Printing Matrices: Used loops to display the resultant matrix.