C program to subtract two matrices; Through this tutorial, we will learn how to subtract two matrices in c programs.
Algorithm to Subtract Two Matrices
Use the following algorithm to write a program to subtract two matrices; as follows:
- START
- Step 1 -> Input matrix 1 and matrix 2.
- Step 2 -> If the number of rows and number of columns of matrix 1 and matrix 2 are equal then execute step 3 else subtraction not possible
- Step 3 -> for i=1 to rows[matrix 1]
- for j=1 to columns [matrix 1]
- Input matrix 1 [i,j]
- Input matrix 2 [i,j]
- matrix 3 [i,j]= matrix 1 [i,j] – matrix 2 [i,j];
- for j=1 to columns [matrix 1]
- step 4-> Display matrix 3 [i,j];
- STOP
C Program to Subtract Two Matrices
/* C Program to Subtract Two Matrices */
#include<stdio.h>
int main()
{
int i, j, rows, columns, a[10][10], b[10][10];
int Subtraction[10][10];
printf("\n Please Enter Number of rows and columns : ");
scanf("%d %d", &i, &j);
printf("\n Please Enter the First Matrix Elements\n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0;columns < j;columns++)
{
scanf("%d", &a[rows][columns]);
}
}
printf("\n Please Enter the Second Matrix Elements\n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0;columns < j;columns++)
{
scanf("%d", &b[rows][columns]);
}
}
for(rows = 0; rows < i; rows++)
{
for(columns = 0;columns < j;columns++)
{
Subtraction[rows][columns] = a[rows][columns] - b[rows][columns];
}
}
printf("\n After Subtracting Matrix a from Matrix b = a - b \n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
printf("%d \t ", Subtraction[rows][columns]);
}
printf("\n");
}
return 0;
}
The output of the above c program; as follow:
Please Enter Number of rows and columns : 3 3 Please Enter the First Matrix Elements 10 20 30 40 50 60 70 80 90 Please Enter the Second Matrix Elements 1 2 3 4 5 6 7 8 9 After Subtracting Matrix a from Matrix b = a - b 9 18 27 36 45 54 63 72 81