Array Sum in C

Level 3114 keystrokes

Calculates the sum of all elements in an integer array using a for loop.

C code

// The numbers to add up
1int arr[] = {1, 2, 3, 4, 5};
// The running total must start at 0 (a local variable is not zeroed automatically)
2int sum = 0;
// Visit indexes 0 to 4
3for (int i = 0; i < 5; i++) {
// Add the current element to the total (same as sum = sum + arr[i])
4 sum += arr[i];
5}
// 1 + 2 + 3 + 4 + 5 gives Sum: 15
6printf("Sum: %d\n", sum);

Output

Sum: 15
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.

  • ;× 6
  • ,× 5
  • =× 4
  • +× 3
  • "× 2
  • (× 2
  • )× 2
  • [× 2
  • ]× 2
  • {× 2

More C examples at level 3

← C typing practice