Here's a program in C++ that declares two 3x3 matrices, calculates their sum, and displays the result.
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 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.
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.
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.
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