2D Array Sum in C

Level 3146 keystrokes

Calculates the sum of all elements in a 2D array using nested loops.

C code

// 2 rows × 3 columns
1int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
// Running total
2int sum = 0;
// Outer loop over the rows
3for (int i = 0; i < 2; i++)
// Inner loop over the columns of row i; no braces are needed for a single statement
4 for (int j = 0; j < 3; j++)
// Runs 2 × 3 = 6 times, once per element
5 sum += m[i][j];
// 1+2+3+4+5+6 gives Sum: 21
6printf("Sum: %d", sum);

Output

Sum: 21
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 8
  • ,× 6
  • +× 5
  • =× 5
  • [× 4
  • ]× 4
  • (× 3
  • )× 3
  • {× 3
  • }× 3

More C examples at level 3

← C typing practice