Array sum in C++ STL
In C++, we can quickly find array sum using accumulate()
// C++ program to demonstrate working of accumulate() #include <iostream> #include <numeric> 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[0]); cout << arraySum(a, n); return 0; } |
chevron_right
filter_none
Output:
30
Sum of vector
// C++ program to demonstrate working of accumulate() #include <iostream> #include <vector> #include <numeric> 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; } |
chevron_right
filter_none
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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Find original array from encrypted array (An array of sums of other elements)
- Find an element in array such that sum of left array is equal to sum of right array
- Find Array formed by adding each element of given array with largest element in new array to its left
- Minimum number of operations to convert array A to array B by adding an integer into a subarray
- Minimum cost to reach end of array array when a maximum jump of K index is allowed
- Minimum number greater than the maximum of array which cannot be formed using the numbers in the array
- Find minimum value to assign all array elements so that array product becomes greater
- Find Kth number from sorted array formed by multiplying any two numbers in the array
- Generate original array from an array that store the counts of greater elements on right
- Print modified array after multiple array range increment operations
- Count number of permutation of an Array having no SubArray of size two or more from original Array
- Maximize the size of array by deleting exactly k sub-arrays to make array prime
- Find starting index for every occurence of given array B in array A using Z-Algorithm
- Check if there exist two elements in an array whose sum is equal to the sum of rest of the array
- Sort an array where a subarray of a sorted array is in reverse order

