# Array sum in C++ STL

In C++, we can quickly find array sum using accumulate()

 `// C++ program to demonstrate working of accumulate() ` `#include   ` `#include       ` `using` `namespace` `std; ` `  `  `// User defined function that returns sum of ` `// arr[] using accumulate() library function. ` `int` `arraySum(``int` `a[], ``int` `n)  ` `{ ` `    ``int` `initial_sum  = 0;  ` `    ``return` `accumulate(a, a+n, initial_sum); ` `} ` `  `  `int` `main()  ` `{ ` `    ``int` `a[] = {5 , 10 , 15} ; ` `    ``int` `n = ``sizeof``(a)/``sizeof``(a); ` `    ``cout << arraySum(a, n); ` `    ``return` `0; ` `} `

Output:

```30
```

Sum of vector

 `// C++ program to demonstrate working of accumulate() ` `#include   ` `#include   ` `#include       ` `using` `namespace` `std; ` `  `  `// User defined function that returns sum of ` `// arr[] using accumulate() library function. ` `int` `arraySum(vector<``int``> &v)  ` `{ ` `    ``int` `initial_sum  = 0;  ` `    ``return` `accumulate(v.begin(), v.end(), initial_sum); ` `} ` `  `  `int` `main()  ` `{ ` `    ``vector<``int``> v{5 , 10 , 15} ; ` `    ``cout << arraySum(v); ` `    ``return` `0; ` `} `

Output:

```30
```

We can also use a custom function in accumulate. Refer numeric header in C++ STL | Set 1 (accumulate() and partial_sum()) for details.

This article is contributed by kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :

11

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.