This is the Matrix Multiplication program code for C++. The coding has been done in Code:Blocks and the source code can be found at the very end. The program is simple and consists of taking input a couple of Matrices and multiplying them using Matrix Multiplication rules. The logic for Matrix Multiplication is as follows in the picture below:
In this code you will be able to multiply variable number of rows with variable number of columns. When the dimensions of the second matrix are entered, the system checks if the multiplication operation can be applied , i.e. the number of columns in the first matrix should be equal to the number of rows in the second matrix.
We apply the for loop twice for reading the Matrix values. The first loop deals with the row number and second loop deals with the column number. The value of the variables in the loops represent the row number and column number of the next matrix element.
#include <iostream>
using namespace std;
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int Mat1[100][100], Mat2[100][100], Result[100][100];
cout<<"Enter the number of rows and columns of first matrix\n";
cin>>m>>n;
cout<<"Enter the elements of first matrix\n";
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
cin>>Mat1[c][d];
cout<<"Enter the number of rows and columns of second matrix\n";
cin>>p>>q;
if ( n != p )
cout<<"Invalid Matrix Columns or Rows.\n";
else
{
cout<<"Enter the elements of second matrix\n";
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
cin>>Mat2[c][d];
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + Mat1[c][k] * Mat2[k][d];
}
Result[c][d] = sum;
sum = 0;
}
}
cout<<"Resultant Matrix is: \n";
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
cout<<"\t"<<Result[c][d];
cout<<"\n";
}
}
return 0;
}
Download Source Code Here. Notice that the C++ Souce Code is written in Code::Blocks 12.11 IDE available for direct download Here.
Please ask your questions and list your suggestions below in the comments section.
Thank you very much
ReplyDelete