The sum of Matrix

// I want to write a program which can add Matrix A and Mathix B, and print the result
#include <iostream>
#include <cstdlib>
#include <iomanip>

using namespace std;

#define ROWS 3    //  3 X 3 matrix
#define COLS 3

class Matrix // define a class Matrix
{
      public:
          void MatrixAdd(int*, int*, int*, int, int);
          void print(int data[ROWS][COLS]);
};

void Matrix::print(int data[ROWS][COLS]) // print the matrix
{
     for(int i = 0; i < ROWS; i++)
     {
         for(int j = 0; j < COLS; j++)
             cout << "[" << setw(3) << data[i][j] << "]" << "\t";
         cout << endl;
     }
}

void Matrix::MatrixAdd(int* arrA, int* arrB, int* arrC, int dimX, int dimY) // add Matrix A and Matrix B
{
     if(dimX <= 0 || dimY <= 0)  // check the dimensions of the matrix
     {
         cout << "The dimensions of the matrix must be positive" << endl;
         return;
     }

     for(int row = 1; row <= dimX; row++)  // do the calculation
         for(int col = 1; col <= dimY; col++)
             arrC[(row-1)*dimY + (col-1)] = arrA[(row-1)*dimY+(col-1)] + arrB[(row-1)*dimY+(col-1)];
}

int main()
{
    int A[ROWS][COLS] = {{31,23,45},{37,65,116},{81,58,157}}; // just create a test data for the program
    int B[ROWS][COLS] = {{89,54,117},{96,55,142},{23,25,278}};
    int C[ROWS][COLS] = {0}; 

    Matrix obj; // obj is a matrix 

    cout << "---Print Matrix A---" << endl << endl;
    obj.print(A);
    cout << endl;
    cout << "---Print Matrix B---" << endl << endl;
    obj.print(B);
    obj.MatrixAdd(&A[0][0],&B[0][0],&C[0][0],ROWS,COLS);
    cout << endl;
    cout << "---Print Matrix A + Matrix B---" << endl << endl;
    obj.print(C);
    system("PAUSE");
    return EXIT_SUCCESS;
}

2 Responses

  1. Hey! Can I ask you a favor?? It’s ok if you don’t want to do it. Can you comment on each line or every major part what those line do?? I mean explanations??

  2. Hey, Dok

    I add a few comments

    (if you don’t understand a specific line, i can add a comment beside it.)

Leave a Reply