This post will discuss how to find the sum of elements in a C++ array.

1. Using STL’s accumulate() function

The standard solution is to use the std::accumulate provided by the standard library. It is defined in the header file numeric. The default operation is to add the elements up to but to make the context more clear. We can also pass a function in the optional fourth parameter, which performs the addition operation on two numbers and return the result.

Download  Run Code

2. Using Boost’s accumulate() function

Another good alternative is to use boost’s accumulate() function, which is defined in the header file boost/range/numeric.hpp.

Download Code

3. Using STL’s for_each() function

We can also write the summation logic in the predicate to the std::for_each standard algorithm. This is demonstrated below using lambdas:

Download  Run Code

4. For-loop / Range-based for-loop

We can also write our own routine for this simple task. The idea is to traverse the array using simple for-loop or range-based for-loop and accumulate the sum of each element in a variable.

⮚ For-loop

Download  Run Code

⮚ Range-based for-loop

Download  Run Code

5. Using valarray sum() function

If the valarray class is used instead of the standard array, the sum operation can be applied directly to the valarray object by calling its member function sum().

Download  Run Code

6. C++17 – Fold Expressions

With C++17, we can use fold expressions, as shown below:

Run Code

That’s all about finding the sum of elements in a C++ array.