Arrays
Add corresponding entries of two small matrices using nested loops.
Complete program
#include <stdio.h>
int main(void) {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int result[2][2];
for (int row = 0; row < 2; ++row) {
for (int col = 0; col < 2; ++col) {
result[row][col] = a[row][col] + b[row][col];
printf("%d%s", result[row][col], col == 1 ? "\n" : " ");
}
}
return 0;
}
Opens a new program without replacing your saved code. Press Run when you are ready.
How it works
Matrix addition requires the same dimensions on both sides. The outer loop selects a row; the inner loop selects each column within that row.
The result is another two-dimensional array. This is element-wise addition, not matrix multiplication. Change the dimensions consistently in declarations and loop bounds when experimenting; a wrong bound can access unrelated memory.
Expected output
6 8
10 12Concepts to practice
- Multidimensional arrays
- Nested loops
- Dimensions
Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.