# C++ program to find the addition of two matrices using class

Given two matrices, we have to find the addition of two matrices using the class and object approach.
Submitted by Shubh Pachori, on August 06, 2022

Example:

```Input:
Enter Matrix A
Enter x : 1
Enter x : 2
Enter x : 3
Enter x : 4
Enter Matrix B
Enter x : 4
Enter x : 3
Enter x : 2
Enter x : 1
Matrix A:
1 2
3 4
Matrix B:
4 3
2 1

Output:
Addition of A and B matrix
5 5
5 5
```

## C++ code to find the addition of two matrices using class and object approach

```#include <iostream>
using namespace std;

// create a class
class Matrix {
// private data members
private:
int x;
int row, col;

// public functions
public:
// getMatrix() function to insert matrix
void getMatrix(int r, int c) {
// initialising a matrix type variable
Matrix M1;

// copying value of parameters in the data members
row = r;
col = c;

// nested for loop for insertion of matrix
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << "Enter x[" << i << "][" << j << "] : ";
cin >> x[i][j];
}
}
}

// putMatrix() function to print the matrix
void putMatrix() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << x[i][j] << " ";
}
cout << "\n";
}
}

// initializing a Matrix type variable
Matrix M;

// copying the value of parameters in the data members
M.row = row;
M.col = col;

// nested for loop to add two matrices
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
M.x[i][j] = x[i][j] + M2.x[i][j];
}
}

// returning the resulted matrix
return (M);
}
};

int main() {
// creating objects
Matrix M1, M2, M3;

// inserting matrix using getMatrix() function
cout << "Enter Matrix A\n" << endl;
M1.getMatrix(2, 2);

cout << "\nEnter Matrix B\n" << endl;
M2.getMatrix(2, 2);

// printing the matrix using putMatrix() function
cout << "\nMatrix A:" << endl;
M1.putMatrix();

cout << endl;

cout << "Matrix B:" << endl;
M2.putMatrix();

cout << "\nAddition of A and B matrix\n" << endl;

// printing the resulted matrix
M3.putMatrix();

return 0;
}
```

Output:

```Enter Matrix A

Enter x : 3
Enter x : 3
Enter x : 3
Enter x : 3

Enter Matrix B

Enter x : 4
Enter x : 4
Enter x : 4
Enter x : 4

Matrix A:
3 3
3 3

Matrix B:
4 4
4 4

Addition of A and B matrix

7 7
7 7
```

Explanation:

In the above code, we have created a class Matrix, three int type data members x, row and col to store the matrix, row, and column, and public member functions getMatrix(), putMatrix() and add() to insert, print and add matrices.

In the main() function, we are creating an object M1, M2, and M3 of class Matrix, reading matrices given by the user using getMatrix() function, and finally calling the add() member function to add the given matrices. The add() function contains the logic to add the given matrices and printing the result.