C++ Program to Check Multiplicability of Two Matrices


Two matrices are said to be multiplicable if they can be multiplied. This is only possible if the number of columns of the first matrix is equal to the number of rows of the second matrix. For example.

Number of rows in Matrix 1 = 3
Number of columns in Matrix 1 = 2

Number of rows in Matrix 2 = 2
Number of columns in Matrix 2 = 5

Matrix 1 and Matrix 2 are multiplicable as the number of columns of Matrix 1 is equal to the number of rows of Matrix 2.

A program to check the multiplicity of two matrices is as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int row1, column1, row2, column2;
   cout<<"Enter the dimensions of the first matrix:"<< endl;
   cin>>row1;
   cin>>column1;
   cout<<"Enter the dimensions of the second matrix: "<<endl;
   cin>>row2;
   cin>>column2;
   cout<<"First Matrix"<<endl;
   cout<<"Number of rows: "<<row1<<endl;
   cout<<"Number of columns: "<<column1<<endl;
   cout<<"Second Matrix"<<endl;
   cout<<"Number of rows: "<<row2<<endl;
   cout<<"Number of columns: "<<column2<<endl;
   if(column1 == row2)
   cout<<"Matrices are multiplicable";
   else
   cout<<"Matrices are not multiplicable";
   return 0;
}

output

Enter the dimensions of the first matrix: 2 3
Enter the dimensions of the second matrix: 3 3
First Matrix
Number of rows: 2
Number of columns: 3

Second Matrix
Number of rows: 3
Number of columns: 3

Matrices are multiplicable

In the above program, first the dimensions of the two matrices are entered by the user. This is shown as follows.

cout<<"Enter the dimensions of the first matrix:"<< endl;
cin>>row1;
cin>>column1;
cout<<"Enter the dimensions of the second matrix: "<<endl;
cin>>row2;
cin>>column2;

After that, the number of rows and columns of the matrices are printed. This is shown below.

cout<<"First Matrix"<<endl;
cout<<"Number of rows: "<<row1<<endl;
cout<<"Number of columns: "<<column1<<endl;
cout<<"Second Matrix"<<endl;
cout<<"Number of rows: "<<row2<<endl;
cout<<"Number of columns: "<<column2<<endl;

If the number of columns in matrix1 is equal to the number of rows in matrix2, then it is printed that the matrices are multiplicable. Otherwise, it is printed that the matrices are not multiplicable. This is demonstrated by the following code snippet.

if(column1 == row2)
cout<<"Matrices are multiplicable";
else
cout<<"Matrices are not multiplicable";

Updated on: 24-Jun-2020

213 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements