Program 4
Program 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;
}
int main() {
int rows, cols;
cout << "Enter the number of rows and columns for the matrices: ";
cin >> rows >> cols;
if (m1.isEqual(m2)) {
cout << "\nMatrix 1 + Matrix 2:\n";
MATRIX m3 = m1 + m2;
m3.display();
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