MATRICS OPERATIONS USING OPERATOR OVERLOADING
/*
DEFINE A CLASS MAT OF SIZE M*N, DEFINE +, -, AND * OPERATOR
OF MAT OBJECTS. WRITE A CPP PROGRAM TO TEST ABOVE CLASS
FOR ABOVE OPERATIONS ON THE MAT OBJECTS
*/
#include <iostream>
#include <iomanip>
class MAT
{
int m,n, mat[100][100];
public:
void operator+(MAT);
void operator-(MAT);
void operator*(MAT);
void getdata();
void display();
};
void MAT::getdata()
{
std::cout<<"Enter m: ";
std::cin>>m;
std::cout<<"Enter n: ";
std::cin>>n;
mat[m][n];
for(int i=0; i<m; i++)
{
for(int j=0; j<n;j++){
std::cout<<"Array["<<i<<"]["<<j<<"]: ";
std::cin>>mat[i][j];}
}
}
void MAT::display()
{
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
std::cout<<mat[i][j]<<" ";
}
std::cout<<std::endl;
}
std::cout<<std::endl;
}
void MAT::operator+(MAT m1)
{
if(m==m1.m && n==m1.n)
{
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
std::cout<<std::setw(3)<<mat[i][j]+m1.mat[i][j];
}
std::cout<<std::endl;
}
}
else
{
std::cout<<"Addition not possible"<<std::endl;
}
}
void MAT::operator*(MAT m2)
{
int sum=0;
if(n==m2.m)
{
for(int i=0; i<m; i++)
{
for(int j=0; j<m2.n; j++)
{
for (int k=0; k<m2.m; k++)
{
sum+=mat[i][k]*m2.mat[k][j];
}
std::cout<<std::setw(4)<<sum;
sum=0;
}
std::cout<<std::endl;
}
}
else
{
std::cout<<"Multiplication not possible"<<std::endl;
}
}
void MAT::operator-(MAT m3)
{
if (m==m3.m && n==m3.n)
{
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
std::cout<<std::setw(3)<<mat[j][j]-m3.mat[i][j];
}
std::cout<<std::endl;
}
}
else
{
std::cout<<"Subtraction not possible"<<std::endl;
}
}
int main()
{
MAT ob1, ob2, add ,sub, mul;
std::cout<<"Enter element in 1st array: "<<std::endl;
ob1.getdata();
std::cout<<"Enter element in 2nd array: "<<std::endl;
ob2.getdata();
std::cout<<"Array 1: "<<std::endl;
ob1.display();
std::cout<<"Array 2: "<<std::endl;
ob2.display();
std::cout<<"Addition: "<<std::endl;
ob1+ob2;
std::cout<<"Subtraction: "<<std::endl;
ob1-ob2;
std::cout<<"Multiplication: "<<std::endl;
ob1*ob2;
}
/*
Enter element in 1st array:
Enter m: 3
Enter n: 3
Array[0][0]: 1
Array[0][1]: 2
Array[0][2]: 3
Array[1][0]: 4
Array[1][1]: 5
Array[1][2]: 6
Array[2][0]: 7
Array[2][1]: 8
Array[2][2]: 9
Enter element in 2nd array:
Enter m: 3
Enter n: 3
Array[0][0]: 9
Array[0][1]: 8
Array[0][2]: 7
Array[1][0]: 6
Array[1][1]: 5
Array[1][2]: 4
Array[2][0]: 3
Array[2][1]: 2
Array[2][2]: 1
Array 1:
1 2 3
4 5 6
7 8 9
Array 2:
9 8 7
6 5 4
3 2 1
Addition:
10 10 10
10 10 10
10 10 10
Subtraction:
-8 -3 2
-5 0 5
-2 3 8
Multiplication:
30 24 18
84 69 54
138 114 90
*/
Comments
Post a Comment