You are on page 1of 4

Matrix Multiplication - The C++ Way

As I promised eariler I have now posted a Matrix Addition And Multiplication, th


is program is achived by passing an Object as an Argument..............
/* Matrix Multiplication by PASSING OBJECT AS AN ARGUMENT */
class Matrix
{
int A[10][10];
int m,n;
public:
Matrix(int a,int b)
{
m = a;
n = b;
}
void readmatrix();
void printmatrix();
void addmatrix(Matrix b);
Matrix operator * (Matrix b);
};
void Matrix::readmatrix()
{
for(int i=0;i< m;i++)
{
for(j=0;j< n;j++)
cin>>A[i][j];
}
}
}
void Matrix::printmatrix()
{
for(int i=0;i< m;i++)
{
for(int j=0;j< n;j++)
{
cout< < A[i][j]<<" ";
}
cout< < endl;
}
}
void Matrix::addmatrix(Matrix b)
{
Matrix c(m,n);
for(int i=0;i< m;i++)
{
for(int j=0;j< n;j++)
{
c.A[i][j]=A[i][j]+b.A[i][j];
}
}
cout< < "The Addition Of The Two Matrices Is:"< < endl; c.printmatrix();
}
Matrix Matrix::operator*(Matrix b)
{
Matrix c(m,m);
for(int i=0;i< m;i++)
{
for(int k=0;k< m;k++)
{
c.A[i][k]=0;
for(int j=0;j< n;j++)
{
c.A[i][k] = A[i][j] * b.A[j][k] + c.A[i][k];
}
}
}
return c;
}
void main()
{
clrscr();
cout< < "Enter Order The Two Square Matrices: " ;
int a;
cin>>a;
Matrix x(a,a);
Matrix y(a,a);
cout< < endl< < "Enter Elements In First Matrix : ";
x.readmatrix();
cout< < endl< < "Enter Elements In The Second Matrix :";
y.readmatrix();
cout< < endl< < "The First Matrix:"< < endl;
x.printmatrix();
cout< < endl< < "The Second Matrix:"< < endl;
y.printmatrix();
x.addmatrix(y);
Matrix c(a,a);
c = x * y;
cout< < "The Multiplication Of The Two Matrices Are:"< < endl;
c.printmatrix();
getch();
}
/****** OUTPUT *******
Enter Order The Two Square Matrices: 3
Enter Elements In First Matrix : 1 0 0 0 1 0 0 0 1
Enter Elements In The Second Matrix :1 0 0 0 1 0 0 0 1
The First Matrix:
1 0 0
0 1 0
0 0 1
The Second Matrix:
1 0 0
0 1 0
0 0 1
The Addition Of The Two Matrices Is:
2 0 0
0 2 0
0 0 2
The Multiplication Of The Two Matrices Are:
1 0 0
0 1 0
0 0 1
*/
Posted by Lionel at 3:46 AM 2 comments
Labels: C++ Program
Operator Overloading,Inheritance
Here's a simple and also a very short program in C++ that makes use of Construct
ors, Operator Overloading (++,--)and Single Inheritance (cause its a simple prog
ram as I mentioned it).......

/* C++ Program For Implementation Of Constructors, Operator Overloading and Inhe


ritance */
class index
{
protected:
int count;
public:
index()
{
count = 0;
}
index(int c)
{
count = c;
}
index operator ++()
{
count++;
}
void display()
{
cout< < endl< < "count = "< < count< < endl;
}
};
class index1 : public index
{
public:
void operator --()
{
count--;
}
};
void main()
{
clrscr();
index1 i;
i++;
i++;
i.display();
i--;
i.display();
getch();
}

You might also like