December 22, 2011

Matrix Operation Using Operator Overloading

#include
#include

class matrix{
private:
int mat[5][5];
int row;
int column;
public:
matrix(int,int);
matrix(matrix&);
void getdata();
matrix operator-(matrix);
matrix operator+(matrix);
matrix operator*(matrix);
void display();
};

matrix::matrix(int r,int c)
{
row=r;column=c;
}

matrix::matrix(matrix& m)
{
row=m.row;
column=m.column;

cout<<"Copy constructor"<for(int i=0;i{
for(int j=0;j{
mat[i][j]=m.mat[i][j];
}
}
}

void matrix::getdata()
{
cout<<"Value input:"<for(int i=0;i{
for(int j=0;j{
cout<<"Value("<cin>>mat[i][j];
}
}


}

matrix matrix::operator+(matrix a)
{
cout<<"Addition operator"<
matrix temp(row,column);

for(int i=0;i{
for(int j=0;j{
temp.mat[i][j]=mat[i][j]+a.mat[i][j];
}
}
return temp;
}

matrix matrix::operator-(matrix a)
{
cout<<"Subtraction operator"<
matrix temp(row,column);

for(int i=0;i{
for(int j=0;j{
temp.mat[i][j]=mat[i][j]-a.mat[i][j];
}
}
return temp;
}

matrix matrix::operator*(matrix a)
{
cout<<"Multiplaction operator"<
matrix temp(row,column);

for (int i=0;i{
for (int j=0;j{
temp.mat[i][j]=0;
for(int k=0;k{
temp.mat[i][j]=temp.mat[i][j]+(mat[i][k]*a.mat[k][j]);
}
}
}

return temp;
}

void matrix::display()
{
cout<<"The matrix is "<for(int i=0;i{
for(int j=0;j{
cout<}
cout<}
}

int main()
{
clrscr();
matrix m1(2,2),m2(2,2),m3(2,2);

m1.getdata();
m2.getdata();

m3=m1+m2;
m3.display();

m3=m1-m2;
m3.display();

m3=m1*m2;
m3.display();

getch();
return 0;
}


Output:

No comments:

Post a Comment