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:

  1. We declare two 2×2 matrices A and B, and a third matrix result to store the difference.
  2. Using nested for loops, we iterate through each row and column.
  3. Inside the loop, we subtract corresponding elements of A and B and store them in result.
  4. 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:

  1. We define two 3×3 matrices A and B, and a result matrix.
  2. Using nested loops, we iterate through all elements of the matrices.
  3. Each element of B is subtracted from the corresponding element of A and stored in result.
  4. 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:

  1. Basic Matrix Subtraction: Using nested loops to subtract corresponding elements.
  2. Implementation with Different Matrix Sizes: Demonstrated with 2×2 and 3×3 matrices.
  3. Printing Matrices: Used loops to display the resultant matrix.