Tuesday 19 May 2015

C++ program to add and subtract two matrices by overriding + , - and = operators

#include<iostream>
using namespace std;
class matrix
{
        int a[10][10],row,col;
        public:
                void getdata();
                int operator==(matrix);
                matrix operator+(matrix);
                matrix operator-(matrix);
                friend ostream&operator<<(ostream &,matrix &);
                matrix(int r,int c)
                {
                        row=r;
                        col=c;
                }
};

void matrix::getdata()
{
        for(int i=0;i<row;i++)
        {
                for(int j=0;j<col;j++)
                        cin>>a[i][j];
        }
}

int matrix::operator==(matrix m2)
{
        if((m2.row==row)&&(m2.col==col))
                return 1;
        else
                return 0;
}
matrix matrix::operator+(matrix m2)
{
        matrix m3(row,col);
        for(int i=0;i<row;i++)
        {
                for(int j=0;j<col;j++)
                        m3.a[i][j]=a[i][j]+m2.a[i][j];
        }
        return m3;
}

matrix matrix::operator-(matrix m2)
{
        matrix m4(row,col);
        for(int i=0;i<row;i++)
        {
                for(int j=0;j<col;j++)
                        m4.a[i][j]=a[i][j]-m2.a[i][j];
        }
        return m4;
}

ostream&operator<<(ostream &out,matrix &m)
{
        for(int i=0;i<m.row;i++)
        {
                for(int j=0;j<m.col;j++)
                        cout<<m.a[i][j]<<"\t";
                cout<<"\n";
        }
        return cout;
}


int main()
{
        int m,n,p,q;
        cout<<"enter the orderof matrix1 \n";
        cin>>m>>n;
        matrix m1(m,n);
        cout<<"enter the order of matrix 2\n";
        cin>>p>>q;
        matrix m2(p,q);
        if(m1==m2)
        {
                cout<<"enter the elements of m1";
                m1.getdata();
                cout<<"enter the elements of m2";
                m2.getdata();
                matrix m3(m,n),m4(m,n);
                m3=m1+m2;
                cout<<"sum=\n"<<m3;
                m4=m1-m2;
                cout<<"diff=\n"<<m4;
        }
        else
                cout<<"matrix are not compatiable\n";
        return 0;
}

No comments:

Post a Comment