How to Correctly Sum Up Numbers
How to Correctly Sum Up Numbers
One of the first examples for loops in probably every programming language course is taking a list of numbers and calculating the sum of them. And in every programming language, it’s trivial to write up a solution:
int sumUpNumbers(std::span<const int> numbers) {
int sum = 0;
for (int i : numbers)
sum += i;
return sum;
}
If you compile this with a modern optimizing compiler, you will even get very efficient vectorized code, that sums millions of integers per second. Nice!