Answer to Question #212995 in C++ for Hemambar

Question #212995
Create a class Matrix to store a m x n matrix. Include necessary constructors and functions to
initialize and display the matrix. Using friend function, find the dot product of two input matrices.
1
Expert's answer
2021-07-03T04:49:34-0400
#include <iostream>
using namespace std;
class Matrix{
    int rows, cols, mat[10][10];
    public:
    Matrix(){
        rows = 0;
        cols = 0;
    }
    Matrix(int r, int c){
        rows = r;
        cols = c;
    }
    Matrix(int r, int c, int mat[10][10]){
        rows = r;
        cols = c;
        for(int i = 0; i < cols; i++)
            for(int j = 0; j < rows; j++)
                this->mat[i][j] = mat[i][j];
    }
    void getdata(){
        cout<<"Enter the matrix contents. \n";
        for(int i = 0; i < cols; i++)
            for(int j = 0; j < rows; j++)
                cin>>mat[i][j];
    }
    void putdata(){
        if(rows == 0 && cols == 0)
            cout<<endl<<"\nNo data present";
        else
            for(int i = 0; i < cols; i++){
                cout<<endl;
                for(int j = 0; j < rows; j++)
                    cout<<mat[i][j]<<"\t";
            }
    }
    friend Matrix dot(const Matrix &a, const Matrix &b);
};
Matrix dot(const Matrix &a, const Matrix &b){
    int mul[10][10];
    for(int i = 0;i < a.rows;i++){    
        for(int j=0;j<a.cols;j++){    
            mul[i][j]=0;    
            for(int k=0;k<a.cols;k++){    
                mul[i][j] += a.mat[i][k]*b.mat[k][j];    
            }    
        }    
    }  
    return Matrix(a.rows, b.cols, mul);
}
int main(){
    Matrix A(3, 3), B(3, 3), C;
    A.getdata();
    B.getdata();
    C = dot(A, B);
    C.putdata();
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS