Program for Matrix Multiplication in C++

Matrix Multiplication in C++

 

Here, in this section we will discuss about the matrix multiplication in C++. Matrix multiplication is possible if it satisfies this condition.

Suppose two matrices are a[][] and b[][], and their dimensions are a [n x m] and b [p x q] the resultant matrix can be found if and only if m = p. Then the order of the resultant matrix m[ ][ ] will be [n x q].

Multiplication of matrix in C++

Algorithm :

  • Take the number of rows and columns from the user.
  • Take two matrix of given rows and columns from the user.
  • Declare a matrix for holding the desired value of the multiplication.
  • Now, process the mathematical approach for matrix multiplication.

C++ Program for matrix multiplication :

#include<bits/stdc++.h>
using namespace std;

int main ()
{
int r, c;

cout<<"Enter number of rows and columns :";
cin>>r>>c;

int a[r][c], b[r][c], mul[r][c];

cout<<"\nEnter the first matrix element=\n";

for(int i=0; i<r; i++){

for(int j=0; j<c; j++)
cin>>a[i][j];
}

cout<<"\nEnter the first matrix element=\n";

for(int i=0; i<r; i++){

for(int j=0; j<c; j++)
cin>>a[i][j];
}

for( int i = 0; i < r; i++){

for (int j = 0; j < c; j++){

mul[i][j] = 0;

for (int k = 0; k < c; k++)
mul[i][j] += a[i][k] * b[k][j];

}

}

for(int i=0; i<r; i++){

for(int j=0; j<c; j++)
cout<<a[i][j]<<" ";

cout<<endl;
}

return 0;
}
Output :

Enter number of rows and columns : 3 3

Enter the first matrix element =

1 2 3

4 5 6

7 8 9

Enter the first matrix element =

1 2 1

3 1 2

0 8 2

Resultant Matrix :

7 28 11

19 61 26

31 94 41