Matrix Subtraction Program in C



Two matrices can be subtracted element by element in C. This is achieved using nested for loops, where the outer loop signifies the row and inner loop signifies the column.

C program to find subtraction of two matrices

The following program is used to add the elements of two matrices in C and output the resultant matrix.

#include <stdio.h>

int main() {
  int r, c;
  printf("Enter the number of rows(r): ");
  scanf("%d", & r);
  printf("Enter the number of columns(c): ");
  scanf("%d", & c);

  int a[r][c], b[r][c];

  printf("\nEnter elements of 1st matrix:\n");

  for (int i = 0; i < r; ++i)
    for (int j = 0; j < c; ++j) {
      printf("Enter element a[%d][%d]: ", i + 1, j + 1);
      scanf("%d", & a[i][j]);
    }

  printf("Enter elements of 2nd matrix:\n");
  for (int i = 0; i < r; ++i)
    for (int j = 0; j < c; ++j) {
      printf("Enter element b[%d][%d]: ", i + 1, j + 1);
      scanf("%d", & b[i][j]);
    }
  int sum[r][c];

  //now subtract elements of two matrices
  for (int i = 0; i < r; ++i)
    for (int j = 0; j < c; ++j) {
      sum[i][j] = a[i][j] - b[i][j];
    }

  //output the result
  printf("\nSum of two matrices: \n");
  for (int i = 0; i < r; ++i)
    for (int j = 0; j < c; ++j) {
      printf("%d   ", sum[i][j]);
      if (j == c - 1) {
        printf("\n\n");
      }
    }

  return 0;
}

Output

Output of this program will be −

Enter the number of rows(r): 3
Enter the number of columns(c): 3

Enter elements of 1st matrix:
Enter element a[1][1]: 11
Enter element a[1][2]: 22
Enter element a[1][3]: 33
Enter element a[2][1]: 44
Enter element a[2][2]: 55
Enter element a[2][3]: 66
Enter element a[3][1]: 77
Enter element a[3][2]: 88
Enter element a[3][3]: 99
Enter elements of 2nd matrix:
Enter element b[1][1]: 10
Enter element b[1][2]: 20
Enter element b[1][3]: 30
Enter element b[2][1]: 40
Enter element b[2][2]: 50
Enter element b[2][3]: 60
Enter element b[3][1]: 70
Enter element b[3][2]: 80
Enter element b[3][3]: 90

Sum of two matrices: 
1   2   3   

4   5   6   

7   8   9   
Advertisements