operator overloading concept using Matrix addition as an example.C++ Program - Computer Programming

Latest

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

Thursday, August 31, 2017

operator overloading concept using Matrix addition as an example.C++ Program

Write a C++ program to illustrate the operator overloading concept using Matrix addition as an example.


Program:

#include<iostream.h>
class Matrix
{
public:
float row,col;
float **arr;
Matrix();
Matrix(float,float);
int inputDim(float,float);
int getMatrix();
Matrix operator+(Matrix);
Matrix operator=(Matrix&);
};
int Matrix::getMatrix()
{
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
cin>>arr[i][j];
return 0;
}
Matrix::Matrix(float r,float c)
{
row=r;
col=c;
arr=new float*[row];
for(int i=0;i<row;i++)
arr[i]=new float[col];
}
Matrix::Matrix()
{row=col=0;
arr=NULL;}
int Matrix::inputDim(float r,float c)
{
row=r;
col=c;
arr=new float*[row];
for(int i=0;i<row;i++)
arr[i]=new float[col];
return 0;
}
Matrix Matrix::operator+(Matrix m)
{
Matrix t;
t.inputDim(m.row,m.col);
for(int i=0;i<m.row;i++)
for(int j=0;j<m.col;j++)
t.arr[i][j]=arr[i][j]+m.arr[i][j];
return t;
}
Matrix Matrix::operator=(Matrix &m)
{
for(int i=0;i<m.row;i++)
for(int j=0;j<m.col;j++)
arr[i][j]=m.arr[i][j];
return *this;
}
int main()
{
int r,c;
int getDimension(int &r,int &c);
int showResult(Matrix);
cout<<"\nEnter the matrix size of A\n";
getDimension(r,c);
Matrix a(r,c);
cout<<"\nEnter the matrix A\n";
a.getMatrix();
cout<<"\nEnter the matrix size of B\n";
getDimension(r,c);
Matrix b(r,c);
cout<<"\nEnter the matrix B\n";
b.getMatrix();
if(a.row==b.row && a.col==b.col)
{
Matrix x(r,c);
x=a+b;
cout<<"\nMatrix A:\n";
showResult(a);
cout<<"\nMatrix B:\n";
showResult(b);
cout<<"\nResultant Matrix:\n";
showResult(x);
}
else
cout<<"\nAddition not possible\n";
return 0;
}
int getDimension(int &r,int &c)
{
cout<<"\nEnter row and column:\n";
cin>>r>>c;
return 0;
}
int showResult(Matrix x)
{
for(int i=0;i<x.row;i++){
for(int j=0;j<x.col;j++)
cout<<x.arr[i][j]<<" ";
cout<<"\n";}
return 0;

}


Sample Output and Input:

Enter the matrix size of A:
Enter rows & columns 2 2
Enter the matrix A:
1 1 1 1
Enter the matrix size of B:
Enter rows & columns 2 2
Enter the matrix B:
1 1 1 1
Matrix A: 1 1 1 1
Matrix B: 1 1 1 1
Resultant Matrix:
2 2
2 2

No comments:

Post a Comment