C++ Program to Add Two Matrices

In this tutorial, we will write a C++ program to add two matrices using multi-dimensional arrays. To understand the coding, you should have knowledge of the following topics in C++ programming:

The program takes the user input for the number of rows and columns then the elements for both the matrices.

Lastly, add both the matrices and store them in a separate array and display the result. Let us go through the program.


C++ Program to Add Two Matrices

During addition or subtraction of matrix, it is important that both of the matrices have the same dimensions such as 2×3 matrix can be added to 2×3 matrix.

#include <iostream>
using namespace std;

int main()
{
  int arr1[50][50], arr2[50][50], sum[50][50];
  int row, col, i, j;

  cout << "Enter the no. of rows: ";
  cin >> row;
  cout << "Enter the no. of columns: ";
  cin >> col;

  // 1st matrix user input
  cout << endl << "Enter 1st Matrix elements: " << endl;
  for (i = 0; i < row; ++i)
    for (j = 0; j < col; ++j)
      cin >> arr1[i][j];

  // 2nd matrix user input
  cout << endl << "Enter 2nd Matrix elements: " << endl;
  for (i = 0; i < row; ++i)
    for (j = 0; j < col; ++j)
      cin >> arr2[i][j];

  // matrix adition
  for (i = 0; i < row; ++i)
    for (j = 0; j < col; ++j)
      sum[i][j] = arr1[i][j] + arr2[i][j];

  // Displaying the result
  cout << endl << "Result of sum of the matrices: " << endl;
  for (i = 0; i < row; ++i)
    for (j = 0; j < col; ++j)
    {
      cout << sum[i][j] << "  ";
      if (j == col - 1)
        cout << endl;
    }

  return 0;
}

Output:

Enter the no. of rows: 2
Enter the no. of columns: 3

Enter 1st Matrix elements:
2
2
2
2
2
2

Enter 2nd Matrix elements:
3
3
3
3
3
3

Result of sum of the matrices:
5 5 5
5 5 5