Saturday 2 February 2013

Multilication of Matrices


The program of multiplication of matrix in c++. we multiply matrix's by rows of first matrix with column of second matrix and store result in third matrix also shown in figure. For multiplication of  matrix it is necessary that row of first should be equal to column of second matrix.


Matrix Multiplication in C++
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
void main()
{
int i, j, k, r1, r2, c1, c2, sum1;
int m1[10][10], m2[10][10], sum[10][10], mult[10][10];
 
cout<<endl<<" Enter the no of rows & column for matrix m1: ";
cin>>r1>>c1;
 
cout<<endl<<" Enter the elements for matrix m1 row wise: ";
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
cin>>m1[i][j];
}
 
cout<<endl<<" Enter the no of row & column for matrix m2 :";
cin>>r2>>c2;
 
cout<<endl<<" Enter the elememts for matrix m2 row wise: ";
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
cin>>m2[i][j];
}
 
cout<<endl<<" The matrix m1 is: ";
for(i=0;i<r1;i++)
{
cout<<endl;
for(j=0;j<c1;j++)
{
cout<<m1[i][j]<<"\t";
}
}
 
cout<<endl<<" The matrix m2 is: ";
for(i=0;i<r2;i++)
{
cout<<endl;
for(j=0;j<c2;j++)
{
cout<<m2[i][j]<<"\t";
}
}
 
if(r1==r2 && c1==c2)
{
cout<<endl<<" The matrix sum is: ";
for(i=0;i<r1;i++)
{
cout<<endl;
for(j=0;j<c1;j++)
{
sum[i][j]=0;
sum[i][j]=m1[i][j]+m2[i][j];
cout<<sum[i][j]<<"\t";
}
}
}
 
else
cout<<endl<<" The matrix sum is not possible";
 
if(c1==r2)
{
cout<<endl<<" The matrix multiplication is: ";
for(i=0;i<r1;i++)
{
cout<<endl;
for(j=0;j<c2;j++)
{
mult[i][j]=0;
sum1=0;
for(k=0;k<r1;k++)
{
mult[i][j]=m1[i][k]*m2[k][j];
sum1=mult[i][j]+sum1;
}
cout<<sum1<<"\t";
}
}
}
else
cout<<endl<<" The multiplication is not possible";
getch();
}

No comments:

Post a Comment