C Program to Print Subtraction of Two Matrices using Array

Ex: Write a C program to subtract two matrices using array. How to write a C program to subtract two matrices using array. C program to subtract two matrices using array.

Input from user: 


Enter elements in 1st matrix of size 3x3: 

1 2 3
4 5 6
7 8 9

Enter elements in 2nd matrix of size 3x3:

1 2 3
4 5 6
7 8 9


Expected output:


Subtraction of matrices=

0 0 0
0 0 0
0 0 0



  • Quick links:
  1. What is array?
  2. For loop


  • Logic of matrix Subtraction:

Matrix Subtraction is done element wise. Means Subtraction of matrices is defined by A-B= A↓ij - B↓ij.

C program to print subtraction of two matrices using array
C program to print subtraction of two matrices using array




  Step by Step logic of the given program:


1. Accept two matrices from user declare varible say arr1 and arr2(use 2 dimensional array to store elements).

2. Store elements one by one in arr1 using: 

for(row=0;row<size;row++)
    {
        for(col=0;col<size;col++)
        {
            scanf("%d", &arr1[row][col]);
        }
    }
Follow same these  steps for arr2.

3. Subtract two matrices arr1-arr2 element wise using:

for(row=0;row<size;row++)
    {
        for(col=0;col<size;col++)
        {
          arr3[row][col] = arr1[row][col] - arr2[row][col];
        }
    }

4. Last print Subtraction of two matrices means resultant matrix arr3.





  C program to print subtraction of two matrices using array:


#include<stdio.h>
#define size 3 // size of the matrix

int main()
{

    int arr1[size][size]; // 1st matrix
int arr2[size][size]; // 2nd Matrix
int arr3[size][size]; // Resultant matrix


    int row, col;

/* input elements in first matrix*/
printf("Enter elements in 1st matrix of size 3x3:\n");

    for(row=0;row<size;row++)
{
for(col=0;col<size;col++)
{
scanf("%d", &arr1[row][col]);
}
}

/* input elements in second matrix */

    printf("\nEnter elements in 2nd matrix  of size 3x3: \n");

    for(row=0; row<size;row++)
{
for(col=0;col<size;col++)
{
scanf("%d", &arr2[row][col]);
}
}


    /* subtract both matrices arr1 and arr2 and store result in matrix arr3*/
for(row=0;row<size;row++)
{
for(col=0;col<size;col++)
    {
  arr3[row][col] = arr1[row][col] - arr2[row][col];
}
}


 /* Print the value of resultant matrix arr3 */ 
printf("\nSubtraction of matrices = \n");

    for(row=0; row<size;row++)
{
for(col=0; col<size;col++)
{
printf("%d ",arr3[row][col]);
}
printf("\n");
}

    return 0;

}



Above program shows the following output:


C program to print subtraction of two matrices using array


Thanks for visiting. If you have any doubts, Feel free to share in the comment section. 
To Explore more C Programming Examples Click Here.

No comments:

Post a Comment

If you have any doubts, please discuss here...👇