Download Our Beta Android App And Help Us Build Awesome Stuff!  Download Now.

C++ Matrix Multiplication using OOP

matrix_multiplication_oop.txt
File size: 1.35 KB

File content type: text/plain

Category: Assignment

Course: B.Tech.

Semester: 4

#include<iostream>

using namespace std;

class Matrix {

private:
    int a[10][10], row, col;

public:
    Matrix(int row = 10, int col = 10) {
        this->row = row;
        this->col = col;
    }

    void getData() {
        cout << "Enter " << (row * col) << " elements:\n";
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                cin >> a[i][j];
            }
        }
    }

    void print() {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                cout << a[i][j] << "\t";
            }
            cout << endl;
        }
    }
    
    // Multiply matrix of current instance with the argument matrix
    Matrix multiply(Matrix b) {
        if (col != b.row) {
            cout << "Matrices cannot be multiplied. Argument Matrix returned\n";
            return b;
        }

        Matrix ans(row, b.col);

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < b.col; j++) {
                ans.a[i][j] = 0;
                for (int k = 0; k < b.row; k++) {
                    ans.a[i][j] += a[i][k] * b.a[k][j];
                }
            }
        }

        return ans;
    }

};

int main() {
    Matrix a(2, 3);
    a.getData();
    a.print();

    Matrix b(3, 2);
    b.getData();
    b.print();

    Matrix c = a.multiply(b);
    c.print();
    return 0;
}

Added by passhojao

Comments