Array sum in C++

Level 3109 keystrokes

Adds up the five elements of a C-style array with an index-based for loop and prints 15.

C++ code

// C-style array; its size 5 is deduced from the initializer
1int arr[] = {1, 2, 3, 4, 5};
// The running total must start at 0
2int sum = 0;
// i goes from 0 to 4, the valid indices of a 5-element array
3for (int i = 0; i < 5; i++) {
// Adds the current element: 1+2+3+4+5
4 sum += arr[i];
5}
// Prints 15
6cout << sum << endl;

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
  • =× 4
  • +× 3
  • [× 2
  • ]× 2
  • {× 2
  • }× 2
  • (× 1

More C++ examples at level 3

← C++ typing practice