Sunday, August 1, 2021

C Program to perform Matrix Subtraction

Matrix Subtraction

We will write a C program to perform matrix subtraction operation.

Key points for subtraction of matrices

  • Two matrices should be of same order (number of rows=number of columns).
  • Subtract the corresponding element of matrices.

Example: Subtraction of matrix of order 3 * 3

Subtraction of Matrix (A-B) is as under:

A - B = C


C Program to perform Matrix Subtraction

Program Code:

#include<stdio.h>
int main()
{
 int A[3][3],B[3][3],C[3][3],i, j;
 //Loops for Reading A matrix
 for ( i = 0; i < 3; i++ ) //related to row
 {
   for ( j = 0; j < 3; j++ ) //related to column
   {
     printf("Matrix A[%d][%d]:",i,j);
     scanf("%d", &A[i][j]) ;
   }   
 }
 //Loops for Reading B matrix
 for ( i = 0; i < 3; i++ ) //related to row
 {
   for ( j = 0; j < 3; j++ ) //related to column
   {
     printf("Matrix B[%d][%d]:",i,j);
     scanf("%d", &B[i][j]) ;
   }   
 }
 printf("Matrix A is as under: \n") ;
 /* Print Matrix A, B */
 for ( i = 0; i < 3; i++ ) //related to row
 {
   for ( j = 0; j < 3; j++ ) //related to column
   {
     printf(" %d\t ",A[i][j] );
   }
   printf("\n");
 }
 printf("Matrix B is as under: \n") ;
 for ( i = 0; i < 3; i++ ) //related to row
 {
   for ( j = 0; j < 3; j++ ) //related to column
   {
     printf(" %d\t ",B[i][j] );
   }
   printf("\n");
 }
 printf("Matrix Subtraction is as under: \n");
 for ( i = 0; i < 3; i++ ) //related to row
 {
   for ( j = 0; j < 3; j++ ) //related to column
   {
     printf(" %d\t ",A[i][j] - B[i][j] );
   }
   printf("\n");
 }
 return 0;
}

Program Output:

Matrix A[0][0]:4
Matrix A[0][1]:5
Matrix A[0][2]:6
Matrix A[1][0]:7
Matrix A[1][1]:8
Matrix A[1][2]:9
Matrix A[2][0]:10
Matrix A[2][1]:11
Matrix A[2][2]:12
Matrix B[0][0]:1
Matrix B[0][1]:3
Matrix B[0][2]:2
Matrix B[1][0]:5
Matrix B[1][1]:4
Matrix B[1][2]:3
Matrix B[2][0]:2
Matrix B[2][1]:3
Matrix B[2][2]:6
Matrix A is as under:
 4        5       6
 7        8       9
 10       11      12
Matrix B is as under:
 1        3       2
 5        4       3
 2        3       6
Matrix Subtraction is as under:
 3        2       4
 2        4       6
 8        8       6

* * * * *

* * * * *