C++ program for addition of two matrices
kw.cpp
#include <iostream>
using namespace std;
class matrix
{
private:
    int a[10][10], b[10][10], c[10][10], i, j, m, n;

public:
    void getdata();
    void calc();
};

void matrix::getdata()
{
    cout<<"———————————————————————————————————————————";
    cout<<"\nProgram to print addition of two matrices\n";
    cout<<"———————————————————————————————————————————";
    cout<<"\nEnter the number of row(s) ";
    cin>>m;
    cout<<"Enter the number of column(s) ";
    cin>>n;
}

void matrix::calc()
{
    if (m && n <= 0 || m * n <= 0)
    {
        cout<<"-------------------------------------------";
        cout<<"\nEnter the the valid number of rows and columns";
        cout<<"\n-------------------------------------------\n";
    }
    else
    {
        cout<<"\nEnter elements for matrix A \n";
        for (i = 1; i <= m; i++)
        {
            for (j = 1; j <= n; j++)
            {
                cout<<"["<<i<<"]"
                    <<"["<<j<<"]=";
                cin>>a[i][j];
            }
            cout<<"\n";
        }

        cout<<"Enter elements for matrix B \n";
        for (i = 1; i <= m; i++)
        {
            for (j = 1; j <= n; j++)
            {
                cout<<"["<<i<<"]"
                    <<"["<<j<<"]=";
                cin>>b[i][j];
            }
            cout<<"\n";
        }

        cout<<"Matrix A is \n";
        for (i = 1; i <= m; i++)
        {
            for (j = 1; j <= n; j++)
            {
                cout<<"\t"<<a[i][j];
            }
            cout<<"\n";
        }

        cout<<"Matrix B is \n";
        for (i = 1; i <= m; i++)
        {
            for (j = 1; j <= n; j++)
            {
                cout<<"\t"<<b[i][j];
            }
            cout<<"\n";
        }

        cout<<"The addition of matrix A and matrix B is\n";
        for (i = 1; i <= m; i++)
        {
            for (j = 1; j <= n; j++)
            {
                c[i][j] = a[i][j] + b[i][j];
                cout<<"\t"<<c[i][j];
            }
            cout<<"\n";
        }
        cout<<"———————————————————————————————————————————\n";
    }
}

int main()
{
    matrix m;
    m.getdata();
    m.calc();
    return 0;
}
Output
kodingwindow@kw:~$ g++ kw.cpp
kodingwindow@kw:~$ ./a.out ——————————————————————————————————————————— Program to print addition of two matrices ——————————————————————————————————————————— Enter the number of row(s) 3 Enter the number of column(s) 3 Enter elements for matrix A [1][1]=1 [1][2]=2 [1][3]=3 [2][1]=4 [2][2]=5 [2][3]=6 [3][1]=7 [3][2]=8 [3][3]=9 Enter elements for matrix B [1][1]=9 [1][2]=8 [1][3]=7 [2][1]=6 [2][2]=5 [2][3]=4 [3][1]=3 [3][2]=2 [3][3]=1 Matrix A is 1 2 3 4 5 6 7 8 9 Matrix B is 9 8 7 6 5 4 3 2 1 The addition of matrix A and matrix B is 10 10 10 10 10 10 10 10 10 ——————————————————————————————————————————— kodingwindow@kw:~$
Advertisement