22

Instead of typing

array[0] + array[1] //.....(and so on)

is there a way to add up all the numbers in an array? The language I'm using would be c++ I want to be able to do it with less typing than I would if I just typed it all out.

3
  • 7
    std::accumulate does just what it says on the tin, which is one reason to use it over a loop. Commented Nov 15, 2014 at 2:48
  • For vectors: stackoverflow.com/questions/3221812/… Commented Jun 17, 2015 at 9:28
  • I've closed it as a duplicate of the corresponding answer for std::vector because it makes no difference in C++. All the answers (range-based for loop, std::accumulate, std::reduce, etc.) equally apply to std::vector and to plain arrays. Commented May 10, 2024 at 7:14

10 Answers 10

51

Here is the idiomatic way of doing this in C++:

int a[] = {1, 3, 5, 7, 9};
int total = accumulate(begin(a), end(a), 0, plus<int>());

Note, this example assumes you have somewhere:

#include <numeric>
using namespace std;

Also see: accumulate docs and accumulate demo.

Sign up to request clarification or add additional context in comments.

6 Comments

Worth noting addition is the default.
Also worth noting that for types other than int, the third argument must be a 0 of the right type, e.g. 0.0 when summing up doubles.
I don't know why or when this changed, but I had to #include <numeric> for this to work. Cppreference.com confirms this.
@dasblinkennight - what if my array is an array of pointers to data such as this - slist->items_per_level = (uint64_t*)malloc(sizeof(uint64_t) * maxLevel);
@gansub This is explained in another Q&A with a pretty nice answer.
|
14

Say you have an int array[N].

You can simply do:

int sum = 0;
for(auto& num : array)
    sum += num;

3 Comments

So much cleaner than accumulate, assuming you have C++11 support, and doesn't require two extra includes.
And by using short variable names, this golfs better than accumulate (even without taking into account the includes). The only advantage of accumulate is self documentation I guess?
@Ciro: This isn't the only advantage of accumulate. If you have int array[100]; and you sort part of it like this sort(a, a + n);, the solution with accumulate allows me to create one-line beautiful summation: int revenue = accumulate(a, a + min(m, n), 0);. You can look up the code where I used it here: codeforces.com - Sereja and Coat Rack
7

Try this:

int array[] = {3, 2, 1, 4};
int sum = 0;

for (int i = 0; i < 4; i++) {
    sum = sum + array[i];
}
std::cout << sum << std::endl;

1 Comment

You should explain your answer. their are many answers for this questions are available and are marked as accepted
4

If you use a valarray, there is a member function sum() for that.

#include <iostream>     // std::cout
#include <valarray>     // std::valarray

int main () {
  std::valarray<int> myvalarray(4);
  myvalarray[0] = 0;
  myvalarray[1] = 10;
  myvalarray[2] = 20;
  myvalarray[3] = 30;
  std::cout << "The sum is " << myvalarray.sum() << '\n';

  return 0;
}

Comments

3

The easiest way I can see to do this is to use a loop. The bonus is that you can use it on any integer array without rewriting much code at all. I use Java more often, so I hope there aren't too many syntax errors, but something like this should work:

int addArray(int[] array, int length){
    int sum=0;
    for(int count=0;count<length;count++){
        sum+=array[count];
    }
    return sum;
}

5 Comments

For C++ "int [] array" needs to be "int *array". Otherwise, it works fine. You could add that you are making a function that uses a loop so in the future they can just call addArray()
@Scooter, The two are equivalent to the compiler in that context.
@chris Look closer. They are doing it the Java way - "int[] array" - not "int array[]". But yeah, I should have used "int array []" as it is clearer than "int *array".
@Scooter, Ah, yes, I didn't notice. I actually prefer int * myself if I have to pick one for a parameter because it isn't silently replaced with a different type there like int[] is; what you see is what you get and then anyone who doesn't know about the transformation won't try to expect sizeof to work or anything.
Up Vote just because of that awesome nick! ;)
3

In C++17, one could use fold expressions:

template<typename ...Ts>
int sum_impl(Ts&& ...a)
{
    return (a + ...);
}

If sum_impl had a constant number of parameters, we could have called it like this:

std::apply(sum_impl, arr);

assuming arr is std::array<int, N>. But since it is variadic, it needs a little push with helpers:

using namespace std;

template <class Array, size_t... I>
int sum_impl(Array&& a, index_sequence<I...>)
{
        return sum_impl(get<I>(forward<Array>(a))...);
}

template <class Array>
int sum(Array&& a)
{
        return sum_impl(forward<Array>(a),
                        make_index_sequence<tuple_size_v<decay_t<Array>>>{});
}

Therefore, assuming these helpers are in place, the code will look something like this:

template<typename ...Ts>
int sum_impl(Ts&& ...a)
{
    return (a + ...);
}

int main()
{
    array<int, 10> arr{0,1,2,3,4,5,6,7,8,9};
    cout << sum(arr) << "\n";
    return 0;
}

Comments

0

We may use user defined function.

Code Snippet :

#include<bits/stdc++.h>
using namespace std;


int sum(int arr[], int n)
{
    int sum=0;

    for(int i=0; i<n; i++)
    {
        sum += arr[i];
    }
    return sum;
}


int main()
{
  int arr[] = {1, 2, 3, 4, 5};
  int n = distance(begin(arr), end(arr));

  int total = sum(arr,n);

  printf("%d", total);

  return 0;
}

Comments

0
int Sum;
for(int& S: List) Sum += S;

1 Comment

Please explain what this is doing, don't just post code
0

If your compiler supports c++17, you may use a combination of Parameter pack and fold expression to achieve this. A template parameter pack is a template parameter that accepts zero or more template arguments, and fold reduces the parameter pack over a binary operator. (+ in this case)

#include <iostream>
#include <array>
#include <utility>

/* 
 * References:
 *   [1] https://en.cppreference.com/w/cpp/language/fold
 *   [2] https://en.cppreference.com/w/cpp/language/parameter_pack
 */


template <typename ...T>
auto sum(T ...args)
{
    return (args + ...);
}

template <typename T, std::size_t ...Is>
auto sum(T t, std::index_sequence<Is...>)
{
    return sum(t[Is]...);
}

int main()
{
    std::array<int, 3> a1 = {1, 4, 3};
    int a2[5] = {1, 2, 3, 4, 0};

    std::cout << "Sum a1 = " << sum(a1, std::make_index_sequence<a1.size()>{}) << "\n";
    std::cout << "Sum a2 = " << sum(a2, std::make_index_sequence<5>{}) << "\n";
    return 0;
}

Comments

0

Adding one more point regarding std::accumulate usage:

When a C-style array is passed to a function then you should explicitly specify the array start and end(one-past-the-end) addresses when you use the std::accumulate.

Example:

#include <numeric>
void outsideFun(int arr[], int n) {
    int sz = sizeof arr / sizeof arr[0]; // 1=decays to a ptr to the 1st element of the arr
    // int sum = accumulate(begin(arr), end(arr), 0); // Error:begin/end wouldn't work here
    int sum = accumulate(arr, arr + n, 0);            // 15 (Method 2 Only works!)
    std::cout << sum;
}

int main() {    
    int arr[] = { 1,2,3,4,5 };
    int sz = sizeof arr / sizeof arr[0];           // 5
    int sum = accumulate(begin(arr), end(arr), 0); // 15 (Method 1 - works)
    int cum = accumulate(arr, arr + sz, 0);        // 15 (Method 2 - works)
    outsideFun(arr, sz);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.