0% found this document useful (0 votes)
11 views

Program 4

Uploaded by

sinchanamd05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Program 4

Uploaded by

sinchanamd05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

4.

Write a C++ program to create class called MATRIX using two-dimensional array
of integers, by overloading the operator == which checks the compatibility of two
matrices to be added and subtracted. Perform the addition and subtraction by
overloading + and – operators respectively. Display the results by overloading the
operator <<. If (m1 == m2) then m3 = m1 +m2 and m4 = m1 – m2 else display
error

#include <iostream>
using namespace std;

class MATRIX {
private:
int rows, cols;
int** data;

public:
// Constructor
MATRIX(int r, int c) : rows(r), cols(c) {
data = new int*[rows];
for (int i = 0; i < rows; ++i) {
data[i] = new int[cols]{0}; // Initialize with zero
}
}

// Destructor
~MATRIX() {
for (int i = 0; i < rows; ++i) {
delete[] data[i];
}
delete[] data;
}

// Method to read matrix data


void read() {
cout << "Enter matrix elements (" << rows << "x" << cols << "):\n";
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
cin >> data[i][j];
}

// Method to display matrix


void display() const {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j)
cout << data[i][j] << " ";
cout << endl;
}
}

// Check if matrices are equal


bool isEqual(const MATRIX& other) const {
return (rows == other.rows && cols == other.cols);
}

// Add two matrices


MATRIX operator+(const MATRIX& other) {
MATRIX result(rows, cols);
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
result.data[i][j] = data[i][j] + other.data[i][j];
return result;
}

// Subtract two matrices


MATRIX operator-(const MATRIX& other) {
MATRIX result(rows, cols);
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
result.data[i][j] = data[i][j] - other.data[i][j];
return result;
}
};

int main() {
int rows, cols;
cout << "Enter the number of rows and columns for the matrices: ";
cin >> rows >> cols;

MATRIX m1(rows, cols), m2(rows, cols);


m1.read();
m2.read();

if (m1.isEqual(m2)) {
cout << "\nMatrix 1 + Matrix 2:\n";
MATRIX m3 = m1 + m2;
m3.display();

cout << "Matrix 1 - Matrix 2:\n";


MATRIX m4 = m1 - m2;
m4.display();
} else {
cout << "Error: Matrices are not compatible for addition and subtraction.\n";
}

return 0;
}
Expected Output:
Enter the number of rows and columns for the matrices: 2 2
Enter matrix elements (2x2):
12
36
24
48
Enter matrix elements (2x2):
5
33
15
40

Matrix 1 + Matrix 2:
17 69
39 88
Matrix 1 - Matrix 2:
73
98

You might also like