Summing a vector in C++

Level 3107 keystrokes

Adds every element of the vector to sum with a range-based for loop and prints "Sum: 15". std::accumulate from <numeric> would do the same in one call.

C++ code

// Creates a vector holding the numbers 1 to 5
1vector<int> v = {1, 2, 3, 4, 5};
// The running total starts at 0
2int sum = 0;
// The range-based for gives n each element in turn, without an index
3for (int n : v) {
// Adds it to the total: 1+2+3+4+5
4 sum += n;
5}
// Prints Sum: 15
6cout << "Sum: " << sum << endl;

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.

  • <× 7
  • ,× 4
  • ;× 4
  • =× 3
  • :× 2
  • "× 2
  • {× 2
  • }× 2
  • (× 1
  • )× 1

More C++ examples at level 3

← C++ typing practice