Matrix Operations

Matrix Operations adding and multiplication 

#include<iostream.h>
#include<conio.h>
#include<process.h>
class mat
{
   int *A;
   int r,c;
   public:
   int err;
     mat()
       {
          err=0;
       }
     ~mat()
       {
          delete []A;
       }
      void getmat();
      void disp_mat();
      friend mat operator + (mat &a,mat &b);
      friend mat operator * (mat &a,mat &b);
};


void mat::getmat()
{
  cout<<"Enter no. of rows & collumns: ";
  cin>>r>>c;
  A=new int[r*c];
  cout<<"\nEnter data elements:\n";
  for(int i=0;i<r;++i)
  for(int j=0;j<c;++j)
    cin>>A[i*c+j];
}


void mat::disp_mat()
{
    if(err==1)
    {
         cout<<"\n\nMATRIX DATA incorrect!\n";
         return;
    }
    cout<<"\nMatrix:\n";

    for(int i=0;i<r;++i)
    {
         for(int j=0;j<c;++j)
         cout<<A[i*c+j]<<" ";
         cout<<"\n";
    }
}

mat operator +(mat&a,mat&b)

{
     if(!(a.r==b.r&&a.c==b.c))
         {
              cout<<"\nSorry! invalid operation ";
              a.err=1;
              return a;
         }
     mat x;
     x.r=a.r;
     x.c=a.c;
     x.A=new int [x.r*x.c];

     for(int i=0;i<a.r;++i)
     for(int j=0;j<a.c;++j)
     x.A[i*x.c+j]=a.A[i*a.c+j]+b.A[i*b.c+j];
 return x;
}

mat operator *(mat &a,mat &b)
{
 if(!(a. c==b.r))
 {
  cout<<"\nSorry! Invalid operation";
  a.err=1;
  return a;
 }
 mat x;
 x.r=a.r;
 x.c=b.c;
 x.A=new int [x.r*x.c];
 int q=a.c;
 int s=0;

 for(int i=0; i<a.r;++i)
 {
    for(int j=0;j<b.c;++j)
    {
         s=0;
         for(int k=0;k<q;++k)
         s+=a.A[i*a.c+k]*b.A[k*b.c+j];
         x.A[i*x.c+j]=s;
    }
 }
 return x;
}

void main()
{
 clrscr();
 int ch;
 cout<<"~~~~~~~~~~MENU~~~~~~~~~~"<<endl;
 cout<<" 1.Addition of two matrices \n 2.Multiplication of two matrices\n 3.EXIT\n";
 cout<<"Enter a choice: ";
 cin>>ch;
 if(ch==3)
 exit(0);
 cout<<"\nEnter data of 1st matrix:\n";
 mat x;
 x.getmat();
 cout<<"\nEnter data of 2nd matrix:\n";
 mat y;
 y.getmat();

 if(ch==1)
 {
    cout<<"\nadding....\n";
    mat z=x+y;
    z.disp_mat();
 }

 if(ch==2)
 {
  cout<<"\nmultiplying.....\n";
  mat z=x*y;
  z.disp_mat();
 }

 getch();
}


Post a Comment

0 Comments