19

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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
ShadowWesley77
  • 365
  • 1
  • 5
  • 16

10 Answers10

49

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.

Stefan
  • 919
  • 2
  • 13
  • 24
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 13
    Worth noting addition is the default. – chris Nov 15 '14 at 04:04
  • 4
    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 `double`s. – Baum mit Augen Dec 18 '16 at 22:59
  • 2
    I don't know why or when this changed, but I had to `#include ` for this to work. [Cppreference.com](http://en.cppreference.com/w/cpp/algorithm/accumulate) confirms this. – Evert Heylen Apr 09 '17 at 10:23
  • @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 Jan 08 '19 at 11:04
  • @gansub This is explained in [another Q&A](https://stackoverflow.com/q/5158578/335858) with a pretty nice answer. – Sergey Kalinichenko Jan 08 '19 at 17:02
  • It stopped being *idiomatic C++* as soon as it started with `int a[]` haha :D – bloody Jan 30 '23 at 20:47
13

Say you have an int array[N].

You can simply do:

int sum = 0;
for(auto& num : array)
    sum += num;
Red Alert
  • 3,786
  • 2
  • 17
  • 24
  • So much cleaner than accumulate, assuming you have C++11 support, and doesn't require two extra includes. – jbo5112 Nov 15 '14 at 03:38
  • 1
    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 Santilli OurBigBook.com Jun 17 '15 at 09:38
  • 2
    @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](http://codeforces.com/contest/368/submission/12620328) – Egor Okhterov Aug 20 '15 at 20:06
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;
Milind Deore
  • 2,887
  • 5
  • 25
  • 40
  • 4
    You should explain your answer. their are many answers for this questions are available and are marked as accepted –  Nov 15 '14 at 05:45
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;
}
jbo5112
  • 824
  • 1
  • 11
  • 18
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;
}
James Westman
  • 2,680
  • 1
  • 15
  • 20
  • 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 Nov 15 '14 at 03:42
  • @Scooter, The two are equivalent to the compiler in that context. – chris Nov 15 '14 at 04:03
  • @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 Nov 15 '14 at 04:07
  • @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. – chris Nov 15 '14 at 04:31
  • Up Vote just because of that awesome nick! ;) – Scott Fraley Mar 16 '17 at 22:46
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;
}
Mohammad Alaggan
  • 3,749
  • 1
  • 28
  • 20
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;
}
rashedcs
  • 3,588
  • 2
  • 39
  • 40
0
int Sum;
for(int& S: List) Sum += S;
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
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;
}
Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
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);
}
SridharKritha
  • 8,481
  • 2
  • 52
  • 43