Open In App

Array sum in C++ STL

Last Updated : 14 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Array sum can be defined as the sum of all elements of an array. In this article, we will learn how to find the array sum using C++ STL.

Examples

Input: arr[] = {5, 10, 15, 11, 9}
Output: 50
Explanation: As 5 + 10 + 15 + 11 + 19 = 50

Input: arr[] = {1, 2, 3, 4, 5}
Output: 15
Explanation: As 1 + 2 + 3 + 4 + 5 = 15

Following are the different STL functions to find the array sum in C++:

Using accumulate()

In C++, STL provide the function std::accumulate() to find the sum of an array elements. It is defined inside the <numeric> header file.

Syntax

std::accumulate(first, last, sum);

where first and last are the iterator to first element and the element just after the last element of the range.

Example

C++
// C++ program to find the array sum using
// of std::accumulate()
#include <bits/stdc++.h>
using namespace std;

int main() {
    int arr[] = {5, 10, 15, 11, 9};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Find array sum using std::accumulate()
    cout << accumulate(arr, arr + n, 0);
    return 0;
}

Output
50

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

Using reduce() (C++ 17 Onwards)

Since C++ 17 onwards, we can use the std::reduce() method to find the sum of all array elements. It is similar to std::accumulate() function and returns the sum of values of elements in the given range. It is also defined inside the <numeric> header file.

Example

C++
// C++ program to find the array sum using
// of std::reduce()
#include <bits/stdc++.h>
using namespace std;

int main() {
    int arr[] = {5, 10, 15, 11, 9};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Find array sum using std::reduce()
    cout << reduce(arr, arr + n, 0);
    return 0;
}


Output

50

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



Next Article
Practice Tags :

Similar Reads