Open In App

Array sum in C++ STL

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

CPP
// 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

Time Complexity: O(n)

Space Complexity: O(1) where n is the size of the array.

Sum of vector:

CPP
// 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

Time Complexity: O(n)

Space Complexity: O(1) where n is the size of the array.

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads