How to add all numbers in an array in C++?

ShadowWesley77 picture ShadowWesley77 · Nov 15, 2014 · Viewed 58.8k times · Source

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.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Nov 15, 2014

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>());

Demo.