#include<iostream.h>
class mat
{
int **matrix;
int row,col;
public:
mat(int r,int c);
void get_element(int a,int b,int value);
int &disp_element(int a,int b);
int getrow() {return row;}
int getcol() {return col;}
friend mat operator + (mat &m1,mat &m2);
friend mat operator - (mat &m1,mat &m2);
~mat()
{
delete matrix;
}
};
mat::mat(int r,int c)
{
matrix=new int*[r];
for(int i=0;i<r;i++)
{
matrix[i]=new int[c];
}
}
void mat::get_element(int a,int b,int value)
{
matrix[a][b]=value;
}
int &mat::disp_element(int a,int b)
{
return matrix[a][b]; // return encountering access violation during runtime , Help!!!
}
mat operator + (mat &m1,mat &m2)
{
int r1=m1.row;
int c1=m1.col;
mat m(r1,c1);
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
int v=m1.disp_element(i,j)+m2.disp_element(i,j);
m.get_element(i,j,v);
}
}
return m;
}
mat operator - (mat &m1,mat &m2)
{
int r1=m1.row;
int c1=m1.col;
mat m(r1,c1);
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
int v=m1.disp_element(i,j)-m2.disp_element(i,j);
m.get_element(i,j,v);
}
}
return m;
}
int main()
{
int x,i,j;
mat m1(2,2);
mat m2(2,2);
cout<<endl<<"Input of m1"<<endl;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"enter element row "<<i+1<<" col "<<j+1<<" :";
cin>>x;
m1.get_element(i,j,x);
}
}
cout<<endl<<endl<<"display of m1"<<endl;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<m1.disp_element(i,j)<<" ";
}
cout<<endl;
}
//------------------------------------------
cout<<endl<<"Input of m2"<<endl;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"enter element row "<<i+1<<" col "<<j+1<<" :";
cin>>x;
m2.get_element(i,j,x);
}
}
cout<<endl<<endl<<"display of m2"<<endl;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<m2.disp_element(i,j)<<" ";
}
cout<<endl;
}
//------------------------------------------
//Addition and Subtraction
int r1=m1.getrow();
int r2=m2.getrow();
int c1=m1.getcol();
int c2=m2.getcol();
mat m3(r1,c1);
mat m4(r1,c1);
if((r1!=r2)||(c1!=c2))
{
cout<<endl<<"Addition and subtraction not possible.";
}
else
{
m3=m1+m2;
m4=m1-m2;
}
//------------------------------------------
cout<<endl<<endl<<"display of Sum"<<endl;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<m3.disp_element(i,j)<<" ";
}
cout<<endl;
}
cout<<endl<<endl<<"display of Difference"<<endl;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<m4.disp_element(i,j)<<" ";
}
cout<<endl;
}
return 0;
}
amitahlawat20 0 Light Poster
Narue 5,707 Bad Cop Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.