A grid of rows and columns. Add up each row with nested loops.
C · beginner · 7 min · 22 steps · free
#include <stdio.h>
int main(void) {
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
int row_sum[2] = {0, 0};
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
row_sum[r] += grid[r][c];
}
}
printf("%d %d\n", row_sum[0], row_sum[1]);
return 0;
}row_sum is created on the stack with the value [0, 0].r is created on the stack with the value 0.c is created on the stack with the value 0.c changes from 0 to 1.row_sum changes from [1, 0] to [3, 0].c changes from 1 to 2.row_sum changes from [3, 0] to [6, 0].c goes out of scope and disappears.r changes from 0 to 1. c is created on the stack with the value 3.c changes from 3 to 0.c changes from 0 to 1.row_sum changes from [6, 4] to [6, 9].c changes from 1 to 2.row_sum changes from [6, 9] to [6, 15].c goes out of scope and disappears.r goes out of scope and disappears.6 15.0.Answer: 12. 3 × 4.
Answer: The first value of the second row. Row first.
← Arrays · Strings: char Arrays and \0 →