Home >> Sem 2 >>Matrix Operations using Operator Overloading
#include<string>
#include<iomanip>
#include<iostream>
using namespace std;
class matrix
{
public:
int r,c,i,j,k;
int **mat;
matrix()
{r=0;c=0;
i=j=k=0;
}
matrix(int row, int col)
{
r = row;
c = col;
mat = new int*[r];
for(int i=0; i<c ; i++)
mat[i] = new int[c];
}
void getdata();
void putdata();
matrix operator *(matrix &bb)
{
matrix temp(r,c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
temp.mat[i][j]=0;
for(k=0;k<c;k++)
temp.mat[i][j] += mat[i][k] * bb.mat[k][j];
}
return temp;
}
matrix operator +(matrix &aa)
{
matrix temp(r,c);
for(i=0;i<c;i++)
for(j=0;j<c;j++)
temp.mat[i][j] = mat[i][j] + aa.mat[i][j];
return temp;
}
matrix operator -(matrix &aa)
{
matrix temp(r,c);
for(i=0;i<c;i++)
for(j=0;j<c;j++)
temp.mat[i][j] = mat[i][j] - aa.mat[i][j];
return temp;
}
};
void matrix::getdata()
{
for (int i1=0;i1<r;i1++)
for(int j1=0;j1<c;j1++)
{
cout<<endl<<"Enter the ["<<i1<<"],["<<j1<<"] element of matrix : ";
cin>>mat[i1][j1];
}
}
void matrix ::putdata()
{
for (int i1=0;i1<r;i1++)
{ for(int j1=0;j1<c;j1++)
{
cout<<setw(4)<<mat[i1][j1];
}
cout<<endl<<endl;
}
}
void main()
{
int row,col;
cout<<endl<<"Enterht e size of ROW : ";
cin>>row;
cout<<endl<<"Enterht e size of COLUMN : ";
cin>>col;
matrix m1(row,col);
cout<<endl<<"ENTER THE ELEMENTS OF FIRST MATRIX"<<endl<<endl;
m1.getdata();
matrix m2(row,col);
cout<<endl<<"ENTER THE ELEMENTS OF SECOND MATRIX"<<endl<<endl;
m2.getdata();
cout<<endl<<"FIRST MATRIX"<<endl<<endl;
m1.putdata();
cout<<endl<<"SECOND MATRIX"<<endl<<endl;
m2.putdata();
matrix m3(row,col);
m3 = m1 + m2;
cout<<endl<<"FIRST + SECOND"<<endl<<endl;
m3.putdata();
matrix m4(row,col);
m4 = m1 - m2;
cout<<endl<<"FIRST - SECOND"<<endl<<endl;
m4.putdata();
matrix m5(row,col);
m5 = m1 * m2;
cout<<endl<<"FIRST * SECOND"<<endl<<endl;
m5.putdata();
cin.get();
}