Array sum in C++ STL

link 0

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;
}

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;
}

Output:

30

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar