C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Matrix Subtraction (2D array)

C Program: Matrix Subtraction (2D array)

C

#include <stdio.h>

 

int main() {

    int a[10][10], b[10][10], diff[10][10];

    int i, j, rows, cols;

 

    // Input number of rows and columns

    printf("Enter number of rows: ");

    scanf("%d", &rows);

    printf("Enter number of columns: ");

    scanf("%d", &cols);

 

    // Input elements of first matrix

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

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            scanf("%d", &a[i][j]);

        }

    }

 

    // Input elements of second matrix

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

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            scanf("%d", &b[i][j]);

        }

    }

 

    // Calculate difference of matrices

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            diff[i][j] = a[i][j] - b[i][j];

        }

    }

 

    // Display the resulting matrix

    printf("\nResultant Matrix (Difference):\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            printf("%d\t", diff[i][j]);

        }

        printf("\n");

    }

 

    return 0;

}

Output

 
INPUT :
Enter number of rows: 2
Enter number of columns: 2

Enter elements of first matrix:
8 7
6 5

Enter elements of second matrix:
4 3
2 1

OUTPUT :
Resultant Matrix (Difference):
4   4
4   4

Explanation

  1. The program reads two matrices a and b with equal dimensions.
  2. Each corresponding element is subtracted (a[i][j] - b[i][j]).
  3. The result is stored in the diff
  4. Finally, the difference matrix is printed in tabular format.