Write a program for multiplication of two matrices using operator overloading.

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<stdlib.h>
class matrix
{
   private:
       int mat[10][10];
       int rc;
   public:
       void size(int n)
       {
        rc=n;
       }
       void matinput();
       void matprint();
       matrix operator *(matrix);
};
void matrix::matinput()
{
   cout<<"\nType "<<rc*rc<<" Elements:";
   for(int i=0;i<rc;i++)
   for(int j=0;j<rc;j++)
   cin>>mat[i][j];
}
void matrix::matprint()
{
  for (int i=0;i<rc;i++)
  {
     for(int j=0;j<rc;j++)
     cout<<mat[i][j]<<setw(6);
     cout<<"\n";
  }
}
matrix matrix:: operator*(matrix m)
{
   matrix matprod;
   matprod.size(rc);
   for(int i=0;i<rc;i++)
   {
       matprod.mat[i][j]=0;
       for(int k=0;k<rc;k++)
       matprod.mat[i][j]=matprod[i][j]+mat[i][k]*m.mat[k][j];
   }
   return matprod;
}
void main()
{
  clrscr();
  matrix A,B,C;
  int rc;
  cout<<"\nType the order of the matrix:";
  cin>>rc;
  A.size(rc);
  B.size(rc);
  C.size(rc);
  cout<<"\nMatrix A:";
  A.matinput();
  cout<<"\nMatrix B:";
  B.matinput();
  cout<<"\nMatrix A:\n";
  A.matprint();
  cout<<"\nMatrix B:\n";
  B.matprint();
  C=A*B;
  cout<<"\nMultiplication of the matrix:\n";
  C.matprint();
  getch();
}

4 comments:

  1. plz help there is a error
    matprod.mat[i][j]=matprod[i][j]+mat[i][k]*m.mat[k][j];
    it cannot multiply

    ReplyDelete
  2. matrix matrix:: operator*(matrix m)
    {
    matrix matprod;
    matprod.size(rc);
    for(int i=0;i<rc;i++)
    {
    matprod.mat[i][j]=0;
    for(int k=0;k<rc;k++)
    matprod.mat[i][j]=matprod[i][j]+mat[i][k]*m.mat[k][j];
    }
    return matprod;
    }

    some error found
    that function is error
    so use this function on that place
    matrix matrix:: operator*(matrix m)
    {
    matrix matprod;
    matprod.size(rc);
    for(int i=0;i<rc;i++)
    for(int j=0;j<rc;j++)
    {
    matprod.mat[i][j]=0;
    for(int k=0;k<rc;k++)
    matprod.mat[i][j]=matprod.mat[i][j]+mat[i][k]* m.mat[k][j];
    }
    return matprod;
    }

    finish
    for(int j=0;j<rc;j++) and matprod.mat[i][j] missing so correct that sir
    but always this program is good

    ReplyDelete