In: Computer Science
In C++ write a function to find a product of two matrices using arrays. The function should be general and should accept any size matrices.
The Program Code is :
///Cpp program for Product of two
Arrays
/// Using Function
#include<iostream>
using namespace std;
void matrix_Multilication(int **m1,int **m2,int r1,int c1,int
c2,int r2)
{
///Function Definition
int i,j,k;
int **m3;
int sum = 0;
m3=new int
*[r1];
for(i = 0;i < r1 ;i++)
{
m3[i]=new
int[c2];///Dynamic memory allocation for Matrix3
}
cout<<"The Matrix 1 is :"<<endl;
for(i = 0; i < r1; i++)
{
for(j = 0; j < c1; j++)
{
cout<<m1[i][j]<<"\t";///It will display Matrix1
Elements
}
cout<<endl;
}
cout<<"The
Matrix 2 is :"<<endl;
for(i = 0; i < r2; i++)
{
for(j = 0; j < c2; j++)
{
cout<<m1[i][j]<<"\t";///It will display Matrix2
Elements
}
cout<<endl;
}
/// Matrix Multiplication logic
for(i = 0; i < r1; ++i)
{
for(j = 0; j < c2;
++j)
{
for(k = 0; k < c1; ++k)
{
sum += m1[i][k] * m2[k][j];
}
m3[i][j] = sum;
sum = 0;
}
}
cout<<"The Product of Matrix
1 and Matrix2 is :"<<endl;
for(i = 0; i < r1; i++)
{
for(j = 0; j < c2; j++)
{
cout<<m3[i][j]<<"\t";///It will display Product
Elements
}
cout<<endl;
}
}
int main()
{
int **m1; ///Double Pointer m1 for 2D Array
int **m2; ///Double Pointer m2 for 2D Array
int i,j,k,r1,c1,r2,c2;
cout<<"Enter Number of Rows and Columns of Matrix 1
"<<endl;
cin>>r1>>c1;
cout<<"Enter Number of Rows
and Columns of Matrix 2 "<<endl;
cin>>r2>>c2;
while(c1 != r2)///It will check Matrix
Multiplication is Possible or Not
{
cout<<" Error : ";
cout<<"Column of matrix 1 and
Rows of matrix 2 Must be Equal "<<endl;
cout<<"Again :
"<<endl;
cout<<"Enter Number of Rows and Columns of Matrix 1
"<<endl;
cin>>r1>>c1;
cout<<"Enter Number of Rows and Columns of Matrix 2
"<<endl;
cin>>r2>>c2;
}
m1=new int *[r1];
for(i = 0;i < r1 ;i++)
{
m1[i]=new
int[c1];///Dynamic memory allocation for Matrix1
}
cout<<"Enter Matrix1 : "<<r1*c1<<"
values"<<endl;
for(i = 0; i < r1;
i++)
{
for(j = 0; j < c1; j++)
{
cin>>m1[i][j];/// It will Read the matrix1 Elements
}
}
m2=new int *[r2];
for(i = 0;i < r2 ;i++)
{
m2[i]=new int[c2];
///Dynamic memory allocation for Matrix2
}
cout<<"Enter
Matrix2 : "<<r2*c2<<" values"<<endl;
for(i = 0; i < r2; i++)
{
for(j = 0; j < c2; j++)
{
cin>>m2[i][j];/// It will Read the matrix2 Elements
}
}
matrix_Multilication(m1,m2,r1,c1,c2,r2);///Function
Calling
return 0;
}