# Multiply Two Matrix

Multiply two matrix” is a standard operation which can be applied over two or more matrices. Here, we are given two matrices of dimension r1*c1 and r2*c2 respectively. Our task is to multiply the following matrices and store the result in resultant matrix.

CONDITION : The two matrices can only be added if the number of rows of first matrix is equal to number of columns of second matrix.

Example:

R1 = 2, C1 =3

R2 = 3 C2 = 2

#### C++ Program to multiply two matrix is as follows:

```/* Program to multiply Two Matrix */
#include<bits/stdc++.h>
using namespace std;
int main()
{
int r1,c1,r2,c2;
// Scan Dimensions of the matrix
cout<<"Enter the dimensions of first matrix:\n";
cin>>r1>>c1;
cout<<"Enter the dimensions of second matrix:\n";
cin>>r2>>c2;

int first[r1][c1];
int second[r2][c2];
int resultant[r1][c2];

// Scan Matrix1 Elements
cout<<"Enter the elements of first matrix:\n";
for(int i = 0 ; i < r1 ; i++)
for(int j = 0 ; j < c1 ; j++)
cin>>first[i][j];

// Scan Matrix2 Elements
cout<<"Enter the elements of second matrix:\n";
for(int i = 0 ; i < r2 ; i++)
for(int j = 0 ; j < c2 ; j++)
cin>>second[i][j];

// Initialize the resultant matrix with 0
for(int i = 0 ; i < r1 ; i++)
for(int j = 0 ; j < c2 ; j++)
resultant[i][j] = 0;

// Multiply matrix
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
for (int k = 0; k < c1; ++k) {
resultant[i][j] += first[i][k] * second[k][j];
}
}
}

//Print Resultant matrix
cout<<"The Resultant Matrix is:\n";
for(int i = 0 ; i < r1 ; i++)
{
for(int j = 0 ; j < c2 ; j++)
{
cout<<resultant[i][j]<<" ";
}
cout<<endl;
}
}

```
```OUTPUT:
Enter the dimensions of first matrix: 2 3
Enter the elements of second matrix:3 2
Enter the elements of first matrix:
1 2 3
1 2 3
Enter the elements of second matrix:
4 5
4 5
4 5
The Resultant Matrix is:
24 30
24 30```

Related Posts: