#include <iostream>
using namespace std;
const int MAX = 10;
int main() {
int matrix1[MAX][MAX], matrix2[MAX][MAX], sum[MAX][MAX];
int rows, cols, i, j;
cout << "Enter number of rows and columns of matrix: ";
cin >> rows >> cols;
cout << "Enter elements of matrix1:" << endl;
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
cin >> matrix1[i][j];
}
}
cout << "Enter elements of matrix2:" << endl;
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
cin >> matrix2[i][j];
}
}
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
cout << "Sum of matrices:" << endl;
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
cout << sum[i][j] << " ";
}
cout << endl;
}
return 0;
}
* In this program, we declare three 2D arrays matrix1
, matrix2
, and sum of size MAX x MAX
. We also declare variables for the number of rows and columns in the matrix.
* We then take input from the user for the elements of both matrices using nested for
loops.
* Next, we add the corresponding elements of the two matrices to get the sum matrix. This is done using another nested for
loop.
* Finally, we print the sum matrix using nested for
loops.
Enter number of rows and columns of matrix: 2 3
Enter elements of matrix1:
4 9 12
1 7 5
Enter elements of matrix2:
3 17 6
9 4 2
Sum of matrices:
7 26 18
10 11 7