In: Computer Science
create a class matrix.Let U and V be the two matrices of type
Int and number of rows and columns are user defined.
Write the following member functions of the class
a) Add
Add the two matrices U and V. For this, add the corresponding
entries, and place their sum in the
corresponding index of the result matrix.
b) Subtract
Subtract the two matrices U and V. For this, subtract the
corresponding entries, and place this answer in
the corresponding index of the result matrix.
c) Multiply
Multiply the two matrices U and V. In matrix multiplication, one
row element of the first matrix is
multiplied by all column elements of second matrix and place result
in matrix
#include<iostream>
using namespace std;
class Matrix
{
private:
int U[10][10], V[10][10], Sum[10][10], Diff[10][10], Pdt[10][10];
int r1, c1, r2, c2;
public:
// Read matrix U and V
void Read()
{
cout << "Enter number of rows of matrix U : ";
cin >> r1;
cout << "Enter number of columns of matrix U : ";
cin >> c1;
cout << "Enter elements of matrix U : " << endl;
for(int i=0; i<r1; i++) {
cout << "Enter elements of row " << i+1 << endl;
for(int j=0; j<c1; j++) {
cin >> U[i][j];
}
}
cout << "Enter number of rows of matrix V : ";
cin >> r2;
cout << "Enter number of columns of matrix V : ";
cin >> c2;
cout << "Enter elements of matrix V : " << endl;
for(int i=0; i<r2; i++) {
cout << "Enter elements of row " << i+1 << endl;
for(int j=0; j<c2; j++) {
cin >> V[i][j];
}
}
}
// ADD matrix U and V
void Add()
{
if(r1 == r2 && c1== c2) {
for(int i=0; i<r1; i++) {
for(int j=0; j<c1; j++) {
Sum[i][j] = U[i][j] + V[i][j];
}
}
cout << "\n SUM OF U & V is " << endl;
for(int i=0; i<r1; i++) {
cout << endl;
for(int j=0; j<c1; j++) {
cout << "\t" << Sum[i][j] ;
}
}
} else {
cout << "\n Can't add Matrices U and V" << endl;
}
}
// SUBTRACT matrix U and V
void Subtract()
{
if(r1 == r2 && c1== c2) {
for(int i=0; i<r1; i++) {
for(int j=0; j<c1; j++) {
Diff[i][j] = U[i][j] - V[i][j];
}
}
cout << "\n DIFFERENCE OF U & V is " << endl;
for(int i=0; i<r1; i++) {
cout << endl;
for(int j=0; j<c1; j++) {
cout << "\t" << Diff[i][j];
}
}
} else {
cout << "\n Can't subtract Matrices U and V" << endl;
}
}
// MULTIPLY matrix U and V
void Multiply()
{
if(r2 == c1) {
for(int i=0; i<r1; i++) {
for(int j=0; j<c2; j++) {
Pdt[i][j] = 0;
for(int k=0; k<r1; k++) {
Pdt[i][j] = Pdt[i][j] + (U[i][k] * V[k][j]);
}
}
}
cout << "\n PRODUCT OF U & V is " << endl;
for(int i=0; i<r1; i++) {
cout << endl;
for(int j=0; j<c2; j++) {
cout << "\t" << Pdt[i][j];
}
}
} else {
cout << "\n Can't multiply Matrices U and V" << endl;
}
}
};
// main function
int main()
{
Matrix m;
m.Read();
m.Add();
m.Subtract();
m.Multiply();
return 0;
}
SAMPLE OUTPUT