Search This Blog

Tuesday 2 February 2016

Addition and Multiplication of matrices using Classes

#include<iostream>
#include<math.h>

using namespace std;

class matrix
{
int m,n,a[10][10];
public:
matrix();
matrix(int,int);
void putdata();
int sum(matrix* ,matrix*);
int mul(matrix* ,matrix*);
void display();
};

matrix::matrix(){}

void matrix::putdata()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cout << "Enter value of element in " << i << " row  and " << j << " column:" << endl;
cin >> a[i][j];
}
}
}

matrix::matrix(int a,int b)
{
m=a,n=b;
}

int matrix::sum(matrix *m1,matrix *m2)
{
if(m1->m != m2->m || m1->n != m2->n)
{
cout << "Matrices are of different order and cannot be added" << endl;
return(0);
}
else
{
m=m1->m;
n=m1->n;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
a[i][j]=m1->a[i][j]+m2->a[i][j];
}
return(1);
}
}

int matrix::mul(matrix *m1,matrix *m2)
{
if(m1->n != m2->m)
{
cout << "Matrices cannot be multiplied" << endl;
return(0);
}
else
{
m=m1->m;
n=m2->n;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=0;
for(int k=0;k<m1->n;k++)
a[i][j]=m1->a[i][k]*m2->a[k][j]+a[i][j];
}
}
return(1);
}
}

void matrix::display()
{
for(int i=0;i<m;i++)
{
cout << "| ";
for(int j=0;j<n;j++)
cout << a[i][j] << " ";
cout << "|" << endl;
}
}

int main()
{
int m,n,flag=-1,ch;
cout << "Enter no. of rows of matrix A" << endl;
cin >> m;
cout << "Enter no. of columns of matrix A" << endl;
cin >> n;
matrix a(m,n);
a.putdata();
cout << "Enter no. of rows of matrix B" << endl;
cin >> m;
cout << "Enter no. of columns of matrix B" << endl;
cin >> n;
matrix b(m,n);
b.putdata();
matrix c;
do
{
cout << "Enter choice " << endl 
<< "1.Sum " << endl
<< "2.Multiplication" << endl
<< "0.Exit" << endl;
cin >> ch;
switch(ch)
{
case 1:
flag=c.sum(&a,&b);
break;
case 2:
flag=c.mul(&a,&b);
break;
}
if(flag!=0)
c.display();
}while(ch!=0);
}



No comments:

Post a Comment