1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
#include <iostream.h>
#include <stdlib.h>
// The Matrix class
class Matrix
{
private:
int m[][];
int colSize;
int rowSize;
public:
void setRowsAndCols()
{
cout<<"Enter the number of rows: ";
cin>>rowSize;
cout<<"Enter the number of columns: ";
cin>>colSize;
}
void setVal(int row, int col, int val)
{
m[row][col] = val;
}
int getVal(int row, int col)
{
return m[row][col];
}
void setMatrix();
int getColSize()
{
return colSize;
}
int getRowSize()
{
return rowSize;
}
};
// Member function to set a matrix
void Matrix::setMatrix()
{
if ((colSize != 0) && (rowSize != 0))
{
for (int x = 0; x <= rowSize-1; x++)
{
for (int y = 0; y <= colSize-1; y++)
{
int val;
cout<<"val"<<x<<y<<":";
cin>>val;
setVal(x,y,val);
}
}
}
else
{
cout<<"Set the matrix size first"<<endl;
setRowsAndCols();
}
}
// Independent function to add two matrices
void addMatrices(Matrix *matrixPtr1, Matrix *matrixPtr2)
{
int m1RowSize, m1ColSize, m2RowSize, m2ColSize;
m1RowSize = matrixPtr1->getRowSize();
m2RowSize = matrixPtr2->getRowSize();
m1ColSize = matrixPtr1->getColSize();
m2ColSize = matrixPtr2->getColSize();
if ((m1RowSize != m2RowSize) || (m1ColSize != m2ColSize))
{
cout<<"ERROR: The matrices dimensions are not equal"<<endl;
}
else
{
int val1, val2, sum;
Matrix *resMatrixPtr = new Matrix;
for (int x = 0; x <= m1RowSize-1; x++)
{
for (int y = 0; y <= m1ColSize-1; y++)
{
val1 = matrixPtr1->getVal(x,y);
val2 = matrixPtr1->getVal(x,y);
cout<<"val1: "<<val1<<endl;
cout<<"val2: "<<val2<<endl;
sum = val1 + val2;
cout<<"the sum: "<<sum<<endl;
resMatrixPtr->setVal(x,y,sum);
}
}
cout<<"The resultant matrix value: ";
cout<<resMatrixPtr->getVal(1,2);
cout<<endl;
delete resMatrixPtr;
resMatrixPtr = NULL;
}
}
int main()
{
Matrix *ptr1 = new Matrix;
ptr1->setRowsAndCols();
ptr1->setMatrix();
Matrix *ptr2 = new Matrix;
ptr2->setRowsAndCols();
ptr2->setMatrix();
addMatrices(ptr1, ptr2);
delete ptr1;
ptr1 = NULL;
delete ptr2;
ptr2 = NULL;
system("PAUSE");
return 0;
}
|