Product of Matrices coderinme

Product of Matrices coderinme

Define a class matrix 2-d dynamic integer matrix using a pointer to pointer and nrows and ncols. Include (i) necessary constructors, destructor and member functions, (ii) operator function to overload * operator to perform matrix multiplication. Write a C++ program to use this class. The program should read two matrices a and b of size mxn and nxp respectively and compute their product matrix. The size of the matrices a and b is to be inputted at run time. (Assume m=3, n=4 and p=3).
Solution:

#include<iostream.h>
#include<conio.h>
class Matrix
{
private:
int **mat;
int nrow,ncol;
public:
Matrix(int m,int n)
{
nrow=m;
ncol=n;
mat=new int*[nrow];
for(int i=0;i<nrow;i++)
{
mat[i]=new int[ncol];
}
}
void input()
{
cout<<endl<<"Enter elements of "<<nrow<<" X "<<ncol<<" matrix:"<<endl;
for(int i=0;i<nrow;i++)
{
for(int j=0;j<ncol;j++)
{
cin>>mat[i][j];
}
}
}
void display(){
cout<<endl;
for(int i=0;i<nrow;i++)
{
for(int j=0;j<ncol;j++)
{
cout<<mat[i][j]<<"\t";
}
cout<<endl;
}
}
void operator*(Matrix y)
{
Matrix res(nrow,y.ncol);
if(ncol==y.nrow)
{
for(int i=0;i<nrow;i++)
{
for(int j=0;j<y.ncol;j++)
{
res.mat[i][j]=0;
for(int k=0;k<ncol;k++)
{
res.mat[i][j]+=mat[i][k]*y.mat[k][j];
}
}
}
res.display();
}
else
cout<<"Matrix can't be multiplied";
}
};
int main()
{
int m1=3,n1=4,m2=4,n2=3;
Matrix mat1(m1,n1);
mat1.input();
Matrix mat2(m2,n2);
mat2.input();
Matrix mat3(m1,n2);
cout<<"\n-----------------------------------------------"<<endl;
cout<<"Product of matrix1 and matrix2 is:"<<endl;
mat1*mat2;
cout<<"\n";
getch();
return 0;
}

For more programs in C++, visit our C++ Coder Archives

Product of Matrices coderinme

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

Leave a reply:

Your email address will not be published.