[Solved] Matrix Addition with C++

Write a program to perform matrix addition. Assume only square matrices of the same dimension.

Input Format:

The input consists of (2*(m*m)+1) integers. The first integer corresponds to m, the number of rows / columns in the matrix . The next m*m integers correspond to the elements in the first matrix. The last m*m elements correspond to the elements in the second matrix. The elements are read in rowwise order, first row first, then second row and so on. Assume that the maximum value of m is 10.

Output Format:

Refer sample output for details.

Sample Input 1:

2

4 5

6 9

1 2

3 4

Sample Output 1:

5 7

9 13

Solution

#include <iostream>
using namespace std;

int main()
{
    int m, a[10][10], b[10][10], c[10][10];
    cin >> m;
    for (int i = 0; i < m; i++)
    {
        // sauravhathi
        for (int j = 0; j < m; j++)
        {
            cin >> a[i][j];
        }
    }
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> b[i][j];
        }
    }
    for (int i = 0; i < m; i++)
    {
        //sauravhathi
        for (int j = 0; j < m; j++)
        {
            c[i][j] = a[i][j] + b[i][j];
        }
    }
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cout << c[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *