Program to add two matrix (2)

0 Suresh Chand March 30, 2021

In this example, we will write a c++ program to add two matrix using multi-dimensional array.

First, we will ask the user for matrix row and column then we will take input and store it in a multidimensional array. Then we will add each element using for loop.

To understand this example, You must have knowledge in following topics

Explanation of program to add two matrix

Program to add two matrix using c plus
Program to add two matrix

CODE:

#include <iostream>
using namespace std;

int main()
{
    int r, c, a[50][50], b[50][50], sum[50][50], i, j;

    cout << "Enter number of rows: ";
    cin >> r;

    cout << "Enter number of columns: ";
    cin >> c;

    cout << endl << "Enter elements of 1st matrix: " << endl;

    // Storing elements of first matrix
    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element a" << i + 1 << j + 1 << " : ";
           cin >> a[i][j];
       }

    // Storing elements of second matrix
    cout << endl << "Enter elements of 2nd matrix: " << endl;
    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element b" << i + 1 << j + 1 << " : ";
           cin >> b[i][j];
       }

    // Adding Two matrices
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
            sum[i][j] = a[i][j] + b[i][j];

    // Displaying the resultant sum matrix.
    cout << endl << "Sum of two matrix is: " << endl;
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
        {
            cout << sum[i][j] << "  ";
            if(j == c - 1)
                cout << endl;
        }

    return 0;
}

The output of above program is

Enter number of rows: 3
Enter number of columns: 3

Enter elements of 1st matrix: 
Enter element a11 : 1
Enter element a12 : 2
Enter element a13 : 3
Enter element a21 : 4
Enter element a22 : 5
Enter element a23 : 6
Enter element a31 : 7
Enter element a32 : 8
Enter element a33 : 9

Enter elements of 2nd matrix:
Enter element b11 : 0
Enter element b12 : 9
Enter element b13 : 8
Enter element b21 : 7
Enter element b22 : 6
Enter element b23 : 5
Enter element b31 : 4
Enter element b32 : 3
Enter element b33 : 2

Sum of two matrix is:
1  11  11
11  11  11
11  11  11
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

Ads Block Detector Powered by codehelppro.com

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System