0

Practise problem by ~s.o.s~

Q. Write a program which performs addition, subtraction, multiplication of matrices. The dimensions of both the matrices would be specified by the user (dynamic memory allocation required). Use of structure or a class to define the matrix would be a good idea. (Expert)

```
#include<iostream>
using namespace std;
class matrix
{
int dim1,dim2;
int **mat;
public:
matrix(int x=2,int y=2)
{
dim1=x;
dim2=y;
mat=new int*[dim1];
for(int i=0;i<dim1;i++)
mat[i]=new int[dim2];
for(int i=0;i<dim1;i++)
for(int j=0;j<dim2;j++)
mat[i][j]=0;
}
int returndim1()
{
return dim1;
}
int returndim2()
{
return dim2;
}
void input()
{
cout<<"Enter the elements of matrix - ";
for(int i=0;i<dim1;i++)
for(int j=0;j<dim2;j++)
cin>>mat[i][j];
}
void out()
{
for(int i=0;i<dim1;i++)
{
cout<<"\n";
for(int j=0;j<dim2;j++)
cout<<mat[i][j]<<" ";
}
}
matrix operator+(matrix x)
{
matrix c(dim1,dim2);
if(dim1==x.returndim1() && dim2==x.returndim2())
{
for(int i=0;i<dim1;i++)
for(int j=0;j<dim2;j++)
c.mat[i][j]=this->mat[i][j]+x.mat[i][j];
return c;
}
else
{
cout<<"Matrix cant be added";
return c;
}
}
matrix operator-(matrix x)
{
matrix c(dim1,dim2);
if(dim1==x.returndim1() && dim2==x.returndim2())
{
for(int i=0;i<dim1;i++)
for(int j=0;j<dim2;j++)
c.mat[i][j]=this->mat[i][j]-x.mat[i][j];
return c;
}
else
{
cout<<"Matrix cant be subtracted";
return c;
}
}
matrix operator*(matrix x)
{
matrix c(dim1,x.returndim2());
if(dim2==x.returndim1())
{
for(int i=0;i<dim1;i++)
for(int j=0;j<x.returndim2();j++)
for(int k=0;k<dim2;k++)
c.mat[i][j]+=this->mat[i][k]*x.mat[k][j];
return c;
}
else
{
cout<<"Matrix cant be multiplied";
return c;
}
}
};
int main()
{
int x,y;
char ch;
do{
cout<<"Enter the dimension of matrix1 -";
cin>>x>>y;
matrix a(x,y);
a.input();
cout<<"\nEnter the dimension of matrix2 -";
cin>>x>>y;
matrix b(x,y);
b.input();
cout<<"\n1.Add\n2.Sub\n3.Multiply\n";
cin>>x;
if(x==1)
(a+b).out();
else if(x==2)
(a-b).out();
else if(x==3)
(a*b).out();
else
cout<<"Wrong choice";
cout<<"\nContinue(y/n)";
cin>>ch;
}while(ch=='y'||ch=='Y');
cin.get();
return 0;
}
```

Hows the coding? How the code can be more optimized?

Whats the complexity?Is it O(n3)?

Is there any better way for solving the above problem?

Any suggestions,comments or recommendations are welcomed.