Write a program to perform addition of two matrices using operator overloading.

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<stdlib.h>
class matrix
{
   private:
       int mat[10][10];
       int rc;
   public:
       void size(int n)
       {
        rc=n;
       }
       void matinput();
       void matprint();
       matrix operator +(matrix);
};
void matrix::matinput()
{
   cout<<"\nType "<<rc*rc<<" Elements:";
   for(int i=0;i<rc;i++)
   for(int j=0;j<rc;j++)
   cin>>mat[i][j];
}
void matrix::matprint()
{
  for (int i=0;i<rc;i++)
  {
     for(int j=0;j<rc;j++)
     cout<<mat[i][j]<<setw(6);
     cout<<"\n";
  }
}
matrix matrix:: operator + (matrix m)
{
   matrix matsum;
   matsum.size(rc);
   for(int i=0;i<rc;i++)
   for(int j=0;j<rc;j++)
   matsum.mat[i][j]=mat[i][j]+m.mat[i][j];
   return matsum;
}
void main()
{
  clrscr();
  matrix A,B,C;
  int rc;
  cout<<"\nType the order of the matrix:";
  cin>>rc;
  A.size(rc);
  B.size(rc);
  C.size(rc);
  cout<<"\nMatrix A:";
  A.matinput();
  cout<<"\nMatrix B:";
  B.matinput();
  cout<<"\nMatrix A:\n";
  A.matprint();
  cout<<"\nMatrix B:\n";
  B.matprint();
  C=A+B;
  cout<<"\nSum of the matrix:\n";
  C.matprint();
  getch();
}

No comments:

Post a Comment