Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 475
ShadowWesley77 Avatar asked Nov 15 '14 02:11

ShadowWesley77


People also ask

Which function finds sum of all the values in an array?

You can also use Python's sum() function to find the sum of all elements in an array.


1 Answers

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.

like image 72
Sergey Kalinichenko Avatar answered Sep 21 '22 12:09

Sergey Kalinichenko