C++ Program for Matrix subtraction

Matrix Subtraction

C++ program to subtract two matrices has been shown here. Two matrices $[A]_{m \times n}$ and $[B]_{p \times q}$ are considered for Subtraction if the number of rows and columns are same in both of the matrices i.e. $m = p$ and $n = q$.






1. C++ Program for matrix Subtraction

Code has been copied
/***************************************
        alphabetacoder.com
    C++ Program for Matrix Subtraction
***************************************/
#include <iostream>

using namespace std;

int main(){
	// declare variables
    int m,n,p,q,i,j;
    int A[10][10]={0},B[10][10]={0};
    
    //take input of the order of first matrix
    cout<<"Enter the number of row and column of first matrix=";
    cin>>m;
    cin>>n;
    
    //take input of the first matrix
    cout<<"Enter the first matrix of order "<<m<<" x "<<n<<" =\n";
    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            cin>>A[i][j];

     //take input of the order of second matrix
    cout<<"Enter the number of row and column of second matrix=";
    cin>>p;
    cin>>q;
    
    //take input of the second matrix
    cout<<"Enter the second matrix of order "<<p<<" x "<<q<<" =\n";
    for(i=0;i<p;i++)
        for(j=0;j<q;j++)
            cin>>B[i][j];
    
    // check if order of matrices are same
    // if not then subtraction of two matrices is not possible
    if(m!=p||n!=q)
        cout<<"\nMatrices are of different order,hence subtraction is not possible";
    else{
        //add each corresponding elements
        // and print the resultant matrix 
        cout<<"The resultant matrix after subtraction:\n";
        for(i=0;i<m;i++){
            for(j=0;j<n;j++)
                cout<<A[i][j]-B[i][j]<<" ";
            cout<<"\n";
        }
    }
    return 0;
}

Output


Case 1:

Enter the number of row and column of first matrix=3 3

Enter the first matrix of order 3 x 3=

3 5 7

4 5 9

0 1 1

Enter the number of row and column of second matrix=2 3

Enter the second matrix of order 2 x 3=

9 4 5

3 7 8

1 2 3

The resultant matrix after Subtraction:=

-6 1 2

1 -2 1

-1 -1 -2



Case 2:

Enter the number of row and column of first matrix=3 3

Enter the first matrix of order 3 x 3=

3 5 7

4 5 9

0 1 1

Enter the number of row and column of second matrix=2 3

Enter the second matrix of order 2 x 3=

9 4 5

3 7 8


Matrices are of different order,hence Subtraction is not possible