Write C++ program to add two matrices

 #include <iostream>

using namespace std;


int main()

{

    int rows, cols, i, j;

    cout << "Enter the number of rows and columns of matrix: ";

    cin >> rows >> cols;


    int matrix1[rows][cols], matrix2[rows][cols], sum[rows][cols];


    cout << "Enter the elements of first matrix:" << endl;

    for (i = 0; i < rows; i++)

    {

        for (j = 0; j < cols; j++)

        {

            cin >> matrix1[i][j];

        }

    }


    cout << "Enter the elements of second matrix:" << endl;

    for (i = 0; i < rows; i++)

    {

        for (j = 0; j < cols; j++)

        {

            cin >> matrix2[i][j];

        }

    }


    cout << "Sum of matrices:" << endl;

    for (i = 0; i < rows; i++)

    {

        for (j = 0; j < cols; j++)

        {

            sum[i][j] = matrix1[i][j] + matrix2[i][j];

            cout << sum[i][j] << " ";

        }

        cout << endl;

    }


    return 0;

}

In this program, we first ask the user to enter the number of rows and columns for the matrices. We create three integer arrays matrix1, matrix2, and sum to store the matrices and their sum respectively.

Then, we use two nested for loops to read the values for the matrices from the user.

We then add the corresponding elements of the two matrices and store the result in the corresponding element of the sum matrix using another set of nested for loops.

Finally, we display the sum matrix by iterating over its rows and columns and printing each element using cout.


Post a Comment

0 Comments