Pages

Saturday, April 4, 2015

Matrices Multiplication Using 2D Arrays In C++

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
void main()
{
//note that for multiplication the columns of first matrix should be equal to rows of second matrix.

//rows1=rows of first matrix and col1=column of first matrix and vice versa.

int rows1,col1,rows2,col2;
int array1[50][50],array2[50][50],product[50][50];
cout<<"Enter number of rows forfirstmatrix:";
cin>>rows1;
cout<<"\n   Enter number of columns for first matrix : ";
cin>>col1;
cout<<"\n   Entering values in first matrix :-";
cout<<endl;
for(int i=0;i<rows1;i++)
{
for(int j=0;j<col1;j++)
{
cout<<"\n   Enter value : ";
cin>>array1[i][j];
}
}
cout<<"\n   First matrix is :";
cout<<endl<<endl;
//"rowsFm" means rows of first matrix, "colFm" means cloumns of first matrix and vice versa.
for(int rowsFm=0;rowsFm<rows1;rowsFm++)
{
for(int colFm=0;colFm<col1;colFm++)
{
cout<<"\t"<<array1[rowsFm][colFm];
}
cout<<endl<<endl;
}
cout<<"\n   Enter number of rows for second matrix : ";
cin>>rows2;
cout<<"\n   Enter number of columns for second matrix : ";
cin>>col2;
cout<<"\n   Entering values in second matrix :-";
cout<<endl;
for(int k=0;k<rows2;k++)
{
for(int l=0;l<col2;l++)
{
cout<<"\n   Enter value :  ";
cin>>array2[k][l];
}
}
cout<<"\n   Second matrix is :";
cout<<endl<<endl;
for(int rowsSm=0;rowsSm<rows2;rowsSm++)
{
for(int colSm=0;colSm<col2;colSm++)
{
cout<<"\t"<<array2[rowsSm][colSm];
}
cout<<endl<<endl;
}
cout<<"\n   The product of matrices is :-";
cout<<endl<<endl;
if(col1==rows2)
{
for(int a=0;a<rows1;a++)
{
for(int b=0;b<col2;b++)
{
product[a][b]=0;
for(int c=0;c<rows2;c++)
{
product[a][b]=product[a][b]+array1[a][c]*array2[c][b];
}
}
}
for(int d=0;d<rows1;d++)
{
for(int e=0;e<col2;e++)
{
cout<<"\t"<<product[d][e];
}
cout<<endl<<endl;
}
}
else 
{
cout<<"\n   Product is not possible.";
}
getch();
}

No comments:

Post a Comment