C++ Program to Overload Arithmetic Operators

Problem:

Write a C++ program to overload arithmetic operators for performing operations on matrix. Write a C++ program to overload addition + operator. Write a C++ program to overload subtraction - operator. Write a C++ program to overload multiplication * operator. Write a C++ program to overload division / operator.

C++ Program / Source Code:

Here is the source code of C++ program to overload arithmetic operators
/* Aim : C++ program to overload arithmetic operators +,-,*,/ to perform operations on the matrix */

#include<iostream>
using namespace std;

class Matrix
{
	int r,c,M[100][100];

	public:

	Matrix()
	{
	r=c=0;
	}

	Matrix (int x,int y)
	{
	r=x;c=y;
	}

	void accept()
	{
	int i,j;
	cout<<"Enter rows and columns:- ";
	cin>>r>>c;

	cout<<"Enter elements of the matrix:- ";
  
	for(i=0;i<r;i++)
	for(j=0;j<c;j++)
		cin>>M[i][j];
	}

	void display()
	{
	int i,j;

		cout<<endl;  

		for(i=0;i<r;i++)
		{
			for(j=0;j<c;j++)
				cout<<M[i][j]<<"\t";
		cout<<endl;
		}
	}

	Matrix operator + (Matrix M2)
	{
		int i,j;
		Matrix tmp(M2.r,M2.c);
  
		if(r==M2.r && c==M2.c)
		{
			for(i=0;i<r;i++)
				for(j=0;j<c;j++)
					tmp.M[i][j]=this->M[i][j]+M2.M[i][j]; 
     
		return tmp;
		}
		else
		{
			cout<<"Number of rows and columns are not matching. \n";
		}
	}

	Matrix operator - (Matrix M2)
	{
		int i,j;
		Matrix tmp(M2.r,M2.c);
  
		if(r==M2.r && c==M2.c)
		{
		for(i=0;i<r;i++)
			for(j=0;j<c;j++)
				tmp.M[i][j]=this->M[i][j]-M2.M[i][j]; 

		return tmp;
		}
		else
		{
		cout<<"Number of rows and columns are not matching. \n";
		}
	}

	Matrix operator * (Matrix M2)
	{
		int i,j,k;
		Matrix tmp(r,M2.c);
  
		if(c==M2.r)
		{
		for(i=0;i<r;i++)
			for(j=0;j<c;j++) 
			{
				tmp.M[i][j]=0; 
				for(k=0;k<M2.r;k++) 
					tmp.M[i][j]+=this->M[i][k]*M2.M[k][j]; 
			} 
		return tmp;
		}
		else
		{
			cout<<"Number of rows and columns are not matching. \n";
		}
	}

};
 
int main()
{
 Matrix M1,M2,M3;

 M1.accept();
 M2.accept();

 cout<<"First matrix is :";
 M1.display();
 cout<<endl<<"Second matrix is :";
 M2.display();

 cout<<endl<<"Addition is: ";
 M3=M1+M2;
 M3.display();

 cout<<endl<<"Subtraction is: ";
 M3=M1-M2;
 M3.display();

 cout<<endl<<"Multiplication is: ";
 M3=M1*M2;
 M3.display();

 return 0;
}

/* Output of above code / Runtime test cases:-

Enter rows and columns:- 2 2
Enter elements of the matrix:- 1 2 3 4     
Enter rows and columns:- 2 2
Enter elements of the matrix:- 1 2 3 4
First matrix is :
1 2 
3 4 

Second matrix is :
1 2 
3 4 

Addition is: 
2 4 
6 8 

Subtraction is: 
0 0 
0 0 

Multiplication is: 
7 10 
15 22 

*/