Write a program in C++ to add two 3 x. 3 matrices. Define proper class, constructor, destructor and methods in the program.
BACHELOR OR COMPUTER APPLIATIONS (BCA) (REVISED)
Term-End Examination
June, 2020
BCS-031 : PROGRAMMING IN C++
Here’s an example of a C++ program that defines a Matrix
class, including a constructor, destructor, and a method to add two 3×3 matrices:
#include <iostream>
class Matrix {
private:
int rows;
int cols;
int **data;
public:
// Constructor to initialize the matrix
Matrix(int numRows, int numCols) : rows(numRows), cols(numCols) {
data = new int *[rows];
for (int i = 0; i < rows; ++i) {
data[i] = new int[cols];
}
}
// Destructor to deallocate memory
~Matrix() {
for (int i = 0; i < rows; ++i) {
delete[] data[i];
}
delete[] data;
}
// Method to input values into the matrix
void inputValues() {
std::cout << "Enter matrix values:" << std::endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cin >> data[i][j];
}
}
}
// Method to add two matrices
Matrix add(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;
}
// Method to display the matrix
void display() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << data[i][j] << " ";
}
std::cout << std::endl;
}
}
};
int main() {
Matrix matrix1(3, 3);
Matrix matrix2(3, 3);
std::cout << "Enter values for matrix 1:" << std::endl;
matrix1.inputValues();
std::cout << "Enter values for matrix 2:" << std::endl;
matrix2.inputValues();
Matrix sumMatrix = matrix1.add(matrix2);
std::cout << "Matrix 1:" << std::endl;
matrix1.display();
std::cout << "Matrix 2:" << std::endl;
matrix2.display();
std::cout << "Sum of matrices:" << std::endl;
sumMatrix.display();
return 0;
}
In this program, we define a Matrix
class with a constructor to allocate memory for the matrix, a destructor to deallocate memory, methods to input values, add matrices, and display matrices. The main
function demonstrates how to use the Matrix
class to add two 3×3 matrices and display the results.