Using Multi-Dimensional Arrays to Compute Sum of Two Matrices in C++

Exercise:

Write a C++ program that adds two matrices in C++ using multi-dimensional arrays.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int row, col, a[100][100], b[100][100], ans[100][100];
    cout << "Insert the number of rows (1-100): ";
    cin >> row;
    cout << "Insert the number of columns (1-100): ";
    cin >> col;
    cout << endl << "Insert value of 1st matrix: " << endl;
    for(int x = 0; x < row; ++x)    //Storing first matrix
        for(int y = 0; y < col; ++y)
        {   
            cout << " position " << x + 1 << y + 1 << " : ";
            cin >> a[x][y];
        }
    cout << endl << "Insert value of 2nd matrix: " << endl;
    for(int x = 0; x < row; ++x)     // Storing second matrix
        for(int y = 0; y < col; ++y)
        {
            cout << " position " << x + 1 << y + 1 << " : ";
            cin >> b[x][y];
        }
    for(int x = 0; x < row; ++x)
        for(int y = 0; y < col; ++y)
            ans[x][y] = a[x][y] + b[x][y];      // addition 
    cout << endl << "After Addition : " << endl;
    for(int x = 0; x < row; ++x)
        for(int y = 0; y < col; ++y)
        {
            cout << ans[x][y] << "  ";
            if(y == col - 1)
            cout << endl;
        }
    return 0;
}
Click Here to View the Output:
Insert the number of rows (1-100): 2
Insert the number of columns (1-100): 2
Insert value of 1st matrix:
 position 11 : 4
 position 12 : 2
 position 21 : 3
 position 22 : 1
Insert value of 2nd matrix:
 position 11 : 2
 position 12 : 3
 position 21 : 1
 position 22 : 4
After Addition :
6  5
4  5
Click Here to View the Explanation:
  • User is asked for the number of rows row and columns col of the matrices that have to be added. The entered number should be between 1 and 100.
  • A for loop is used to store the elements of 1 matrix.
  • Another for loop is used to store the elements of the second matrix.
  • A nested for loop is used to compute the sum of both the matrices.
  • To print the resultant on the screen, a nested for loop is used.
%d bloggers like this: