New Tutorials:

# C++ Program to Add two Matrices (2D Arrays)

Hello Everyone!

In this tutorial, we will learn how to find the Addition of two Matrices (2D Arrays), in the C++ programming language.

Matrix Addition is a binary operation that produces a single matrix as a result by addition of the corresponding elements of the two matrices.

Constraint: For Matrix Addition, there is one necessary condition - Both the matrices should have the same dimensions i.e. same number of rows and columns.

The result matrix has the same dimension as that of the two matrices that have got added.

In general, an element a[i][j] of the product matrix is formed by adding the m1[]i[j] and m2[i][j], i.e. the 1st element of the matrix product is found by adding the first element of the both the matrices (corresponding elements), 2nd element is formed by adding 2nd elements of both the matrices and so on.

For better understanding, refer to the well commented code given below.

Code:

``````#include <iostream>

using namespace std;

int main() {
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " =====  Program to demonstrate Addition of two Matrices ===== \n\n";

//loop variable i to iterate rows and j to iterate columns.
int row, col, i, j;

//Declaring the 3 matrices (2D arrays) m1-first matrix, m2- second matrix and sum- stores the addition of the two matrices
int m1, m2, sum;

cout << "\n\nEnter the number of Rows and Columns of matrix : ";
cin >> row >> col;

cout << "\nEnter the " << row * col << " elements of first matrix : \n";

for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cin >> m1[i][j];
}
}

cout << "\nEnter the " << row * col << " elements of second matrix : \n";

for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cin >> m2[i][j];
}
}

//calculating the sum matrix
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
sum[i][j] = m1[i][j] + m2[i][j];
}
}

cout << "\n\nThe first matrix is : \n";

for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cout << m1[i][j] << "  ";
}
cout << endl;
}

cout << "\n\nThe second matrix is : \n";

for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cout << m2[i][j] << "  ";
}
cout << endl;
}

cout << "\n\nThe Sum matrix is : \n";

for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cout << sum[i][j] << "  ";
}

cout << endl;
}

cout << "\n\n";

return 0;
}``````

Output: We hope that this post helped you develop better understanding of the Matrix Addition concept and its implementation in C++. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )