Write a C++ program using the concept of OOP for the addition of two Matrices of the same size
Algorithm:
- Create a class called "Matrix"
- Define variables for rows, columns, and a 2D array to store the matrix elements
- Create a constructor to initialize the rows and columns, and allocate memory for the 2D array
- Create a method called "add" that takes another Matrix object as an argument, and performs the addition of the two matrices
- Create a method called "display" to print the elements of the matrix
- Create an object of the Matrix class and use the methods to add two matrices and display the result
C++ Program:
#include <iostream>
using namespace std;
class Matrix {
int rows, columns;
int **mat;
public:
Matrix(int r, int c) {
rows = r;
columns = c;
mat = new int*[rows];
for(int i = 0; i < rows; i++)
mat[i] = new int[columns];
}
void add(Matrix b) {
for(int i = 0; i < rows; i++)
for(int j = 0; j < columns; j++)
mat[i][j] += b.mat[i][j];
}
void display() {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
~Matrix() {
for(int i = 0; i < rows; i++)
delete[] mat[i];
delete[] mat;
}
};
int main() {
int r, c;
cout << "Enter the number of rows and columns: ";
cin >> r >> c;
Matrix a(r, c), b(r, c);
cout << "Enter elements of first matrix: " << endl;
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
cin >> a.mat[i][j];
cout << "Enter elements of second matrix: " << endl;
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
cin >> b.mat[i][j];
a.add(b);
cout << "Resultant matrix: " << endl;
a.display();
return 0;
}
/*
======Input/Output=====
Enter the number of rows and columns: 2 2
Enter elements of first matrix:
1 2
3 4
Enter elements of second matrix:
2 3
4 5
Resultant matrix:
3 5
7 9
*/
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment