Answer to Question #182443 in C++ for P. Gokul

Question #182443

Write a program to negate the value of the object  which has matrix of elements using unary minus operator overloading.


1
Expert's answer
2021-04-17T03:07:46-0400
#include <iostream>
#include <iomanip>
using namespace std;
class Matrix{
    int rows, cols, mat[10][10];
    void getdata(){
        cout<<"Enter the matrix contents. \n";
        for(int i = 0; i < this->cols; i++)
            for(int j = 0; j < this->rows; j++)
                cin>>mat[i][j];
    }
    public:
    Matrix(){
        rows = 0;
        cols = 0;
    }
    Matrix(int r, int c){
        this->rows = r;
        this->cols = c;
        this->getdata();
    }
    void showdata(){
        if(this->rows == 0 && this->cols == 0)
            cout<<endl<<"\nNo data present";
        else
            for(int i = 0; i < this->cols; i++){
                cout<<endl;
                for(int j = 0; j < this->rows; j++)
                    cout<<setw(3)<<mat[i][j];
            }
            cout<<endl;
    }
    Matrix operator-(){
        Matrix* A = this;
        for(int i = 0; i < A->cols; i++)
            for(int j = 0; j < A->rows; j++)
                A->mat[i][j] *= -1;
        return *A;
    }
};
int main(){
    int rows, cols;
    cout<<"Enter number of rows: ";
    cin>>rows;
    cout<<"Enter number of columns: ";
    cin>>cols;
    Matrix A(rows, cols);
    A.showdata();
    Matrix B = -A;
    B.showdata();
    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