This program prompts the user to enter the number of rows and columns for the matrices.
It then takes user input for the elements of matrices A and B.
The program performs matrix addition and displays the original matrices A and B, along with the result of the addition.
#include
using namespace std;
int main() {
int rows, cols;
cout << "Enter the number of rows: ";
cin >> rows;
cout << "Enter the number of columns: ";
cin >> cols;
int matrixA[rows][cols];
int matrixB[rows][cols];
int result[rows][cols];
cout << "Enter elements of matrix A:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrixA[i][j];
}
}
cout << "Enter elements of matrix B:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrixB[i][j];
}
}
// Matrix addition
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrixA[i][j] + matrixB[i][j];
}
}
// Print matrices
cout << "Matrix A:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrixA[i][j] << " ";
}
cout << endl;
}
cout << "Matrix B:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrixB[i][j] << " ";
}
cout << endl;
}
cout << "Sum of matrices A and B:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of matrix A:
1
2
3
4
Enter elements of matrix B:
1
2
3
4
Matrix A:
1 2
3 4
Matrix B:
1 2
3 4
Sum of matrices A and B:
2 4
6 8
