Wednesday, 22 April 2015

C++ Program to perform Matrix Multiplication







PROGRAM

#include<iostream>
#define max 10
using namespace std;
int main ()
{
int p[max][max],q[max][max],s[max][max],i,j,r,c,m,n,k;
cout<<"\nEnter the order of first matrix:\n";
cin>>r>>c;
cout<<"\nEnter the order of second matrix:\n";
cin>>m>>n;
if(c!=m)
{
cout<<"\nSorry the matrices can not be multiplied.\n";
}
else
{cout<<"\nEnter the elements of first matrix:\n";
for(i=0;i<=r-1;i++)
{
for(j=0;j<=c-1;j++)
{
cin>>p[i][j];
}
}
cout<<"\nEnter the elements of second matrix:\n";
for(i=0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
cin>>q[i][j];
}
}

for(i=0;i<=r-1;i++)

{
for(j=0;j<=n-1;j++)
{
s[i][j]=0;
}
}
for(i=0;i<=r-1;i++)
{
for(j=0;j<=n-1;j++)
{
for(k=0;k<=c-1;k++)
{s[i][j]=s[i][j]+p[i][k]*q[k][j];
}
}
}
cout<<"\nThe first matrix is:\n";
for(i=0;i<=r-1;i++)
{
for(j=0;j<=c-1;j++)
{
cout<<p[i][j]<<"\t";
}cout<<"\n";
}
cout<<"\nThe second matrix is:\n";
for(i=0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
cout<<q[i][j]<<"\t";
}
cout<<"\n";
}
cout<<"\nThe resultant matrix is:\n";
for(i=0;i<=r-1;i++)
{
for(j=0;j<=n-1;j++)
{
cout<<s[i][j]<<"\t";
}
cout<<"\n";
}
}return 0;
}




OUTPUT

Enter the order of first matrix:

3
3

Enter the order of second matrix:
3
4

Enter the elements of first matrix:
4
5
6
7
8
9
10
11
12

Enter the elements of second matrix:
7
8
9
10
11
12
13
14
15
16
17
18

The first matrix is:
4 5 6
7 8 9
10 11 12

The second matrix is:
7 8 9 10
11 12 13 14
15 16 17 18

The resultant matrix is:
173 188 203 218
272 296 320 344
371 404 437 470

No comments :

Post a comment

Related Posts Plugin for WordPress, Blogger...