Array Sum with Loop in C

Level 3109 keystrokes

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

C code

// Five elements to add
1int arr[] = {1, 2, 3, 4, 5};
// Start the total at 0 before adding anything
2int sum = 0;
// i takes the indexes 0 to 4; the 5 must match the array length
3for (int i = 0; i < 5; i++) {
// Add the current element to the total
4 sum += arr[i];
5}
// Print the total: 1+2+3+4+5 = 15
6printf("%d\n", sum);

Output

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