This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Sunday, March 12, 2023

Write a program to declare two 3*3 matrices, calculate and display their sum.

 Here's a program in C++ that declares two 3x3 matrices, calculates their sum, and displays the result.

#include <iostream>
using namespace std;

int main() {
    const int ROWS = 3;
    const int COLS = 3;

    // Declare matrices
    int matrix1[ROWS][COLS], matrix2[ROWS][COLS], sum[ROWS][COLS];

    // Input elements of matrices
    cout << "Enter elements of matrix1: " << endl;
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            cin >> matrix1[i][j];
        }
    }
    cout << "Enter elements of matrix2: " << endl;
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            cin >> matrix2[i][j];
        }
    }

    // Calculate sum of matrices
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            sum[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }

    // Display sum of matrices
    cout << "Sum of matrices: " << endl;
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            cout << sum[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

In this program, we first declare three 3x3 integer arrays matrix1, matrix2, and sum, which will be used to store the elements of the matrices and their sum, respectively.

const int ROWS = 3;
const int COLS = 3;
int matrix1[ROWS][COLS], matrix2[ROWS][COLS], sum[ROWS][COLS];

We then use nested loops to input the elements of matrix1 and matrix2 from the user.

// Input elements of matrices
cout << "Enter elements of matrix1: " << endl;
for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLS; j++) {
        cin >> matrix1[i][j];
    }
}
cout << "Enter elements of matrix2: " << endl;
for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLS; j++) {
        cin >> matrix2[i][j];
    }
}

After that, we use nested loops again to calculate the sum of the two matrices and store the result in the sum array.

// Calculate sum of matrices
for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLS; j++) {
        sum[i][j] = matrix1[i][j] + matrix2[i][j];
    }
}

Finally, we use nested loops one more time to display the elements of the sum array, which represents the sum of the two matrices.

 // Display sum of matrices
    cout << "Sum of matrices: " << endl;
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            cout << sum[i][j] << " ";
        }
        cout << endl;
    }

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget