Matrix Multiplication Using Templates

//Template
//OOMP - 9 February 2014
//Mayur Bhangale

#include<iostream>
using namespace std;

template<class T>
class matrix
{
 T x[3][3];
public:
 void getmatrix();
 void showmatrix();
 void addition(matrix<T>);
 void subtraction(matrix<T>);
 void multiplication(matrix<T>,matrix<T>);
};

template<class T>
void matrix<T>::getmatrix()
{
 int i,j;
 cout<<"\n Enter values of matrix :\n";
 for(i=0;i<3;i++)
    {
     for(j=0;j<3;j++)
        {
  cin>>x[i][j];
        }
    }
}

template<class T>
void matrix<T>::showmatrix()
{
 int i,j;
 cout<<"\n\t Matrix ::";
 for(i=0;i<3;i++)
    {
     cout<<"\n";
     for(j=0;j<3;j++)
        {
  cout<<"\t"<<x[i][j];
        }
    }
}

template<class T>
void matrix<T>::addition(matrix<T> b)
{
 int i,j;
 for(i=0;i<3;i++)
    {
     for(j=0;j<3;j++)
        {
  x[i][j]=x[i][j]+b.x[i][j];
        }
     }
}

template<class T>
void matrix<T>::subtraction(matrix<T> b)
{
 int i,j;
 for(i=0;i<3;i++)
    {
     for(j=0;j<3;j++)
        {
  x[i][j]=x[i][j]-b.x[i][j];
        }
     }
}

template<class T>
void matrix<T>::multiplication(matrix<T> b,matrix<T> a)
{
 int i,j,k;
 for(i=0;i<3;i++)
 {
     for(j=0;j<3;j++)
        {
  x[i][j]=0;
        }
 }

for(i=0;i<3;i++){
for(j=0;j<3;j++)
        {
  for(k=0;k<3;k++)
      {
      x[i][j]=x[i][j]+(a.x[i][k]*b.x[k][j]);
      }
        }
     }
}

int main()
{
 int ch;
 matrix<int> a1,b1,c1;
 matrix<float> a2,b2,c2;
 do
   {
    cout<<"\n\t------MENU-------";
    cout<<"\n\t 1.Integer Addition";
    cout<<"\n\t 2.Integer Subtraction";
    cout<<"\n\t 3.Integer Multiplication";
    cout<<"\n\t 4.Float Addition";
    cout<<"\n\t 5.Float Subtraction";
    cout<<"\n\t 6.Float Multiplication";
    cout<<"\n\t Enter your choice";
    cin>>ch;
    switch(ch)
    {
    case 1:a1.getmatrix();
      a1.showmatrix();
      b1.getmatrix();
    b1.showmatrix();
    a1.addition(b1);
      a1.showmatrix();
     break;

    case 2:a1.getmatrix();
      a1.showmatrix();
      b1.getmatrix();
      b1.showmatrix();
      a1.subtraction(b1);
      a1.showmatrix();
     break;

    case 3:a1.getmatrix();
      a1.showmatrix();
      b1.getmatrix();
      b1.showmatrix();
      c1.multiplication(b1,a1);
      c1.showmatrix();
     break;

    case 4:a2.getmatrix();
      a2.showmatrix();
      b2.getmatrix();
      b2.showmatrix();
      a2.addition(b2);
      a2.showmatrix();
     break;

    case 5:a2.getmatrix();
      a2.showmatrix();
      b2.getmatrix();
      b2.showmatrix();
      a2.subtraction(b2);
      a2.showmatrix();
     break;

    case 6:a2.getmatrix();
      a2.showmatrix();
    b2.getmatrix();
      b2.showmatrix();
      c2.multiplication(b2,a2);
      c2.showmatrix();
     break;
    }
  }while(ch!=7);
return 0;
}
SHARE
    Blogger Comment
    Facebook Comment