Program
Time Complexity: O(m*n) where m and n are the number of rows and columns in matrix.
Space Compexity: 0(1)
m=max(r1,r2)
n=max(c1,c2)
#include <stdio.h>
int main()
{
printf("****************************************************");
printf("\n****************************************************");
printf("\n** WAP to subtract two matrices or 2D arrays **");
printf("\n** Created by Sheetal Garg **");
printf("\n** Assistant Professor **");
printf("\n** Phone No:9467863365 **");
printf("\n****************************************************");
printf("\n****************************************************\n");
int r1, c1, r2, c2, i, j, a[5][5], b[5][5], c[5][5], p = 1;
printf("Enter no. of rows and columns of first matrix\n");
scanf("%d%d", &r1, &c1);
printf("Enter no. of rows and columns of second matrix\n");
scanf("%d%d", &r2, &c2);
if (r1 == r2 && c1 == c2)
{
printf("enter elements of first matrix\n");
for (i = 0; i < r1; i++)
for (j = 0; j < c1; j++)
scanf("%d", &a[i][j]);
printf("enter elements of second matrix\n");
for (i = 0; i < r2; i++)
for (j = 0; j < c2; j++)
scanf("%d", &b[i][j]);
for (i = 0; i < r1; i++)
for (j = 0; j < c1; j++)
c[i][j] = a[i][j] - b[i][j];
printf("\nThe first matrix is\n");
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
printf("%d\t", a[i][j]);
printf("\n");
}
printf("\nThe second matrix is\n");
for (i = 0; i < r2; i++)
{
for (j = 0; j < c2; j++)
printf("%d\t", b[i][j]);
printf("\n");
}
printf("\nThe resultant matrix subtraction is\n");
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
printf("%d\t", c[i][j]);
printf("\n");
}
}
else
printf("\nmatrices cant be subtracted");
return 0;
}
Output 1
**************************************************** **************************************************** ** WAP to subtract two matrices or 2D arrays ** ** Created by Sheetal Garg ** ** Assistant Professor ** ** Phone No:9467863365 ** **************************************************** **************************************************** Enter no. of rows and columns of first matrix 3 4 Enter no. of rows and columns of second matrix 2 3 matrices cant be subtracted
Output 2
enter elements of first matrix 4 3 2 5 4 2 6 2 1 enter elements of second matrix 2 3 4 1 2 1 2 1 1 The first matrix is 4 3 2 5 4 2 6 2 1 The second matrix is 2 3 4 1 2 1 2 1 1 The resultant matrix subtraction is 2 0 -2 4 2 1 4 1 0