# How to sum up elements of a C++ vector?

C++Server Side ProgrammingProgramming

Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.

## Algorithm

Begin
Declare v of vector type.
Initialize some values into v vector in array pattern.
Print “Sum of all the elements are:”.
Call accumulate(v.begin(),v.end(),0) to calculate the sum of all
values of v vector.
Print the result of sum.
End.

## Example Code

Live Demo

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
vector<int> v = {2,7,6,10};
cout<<"Sum of all the elements are:"<<endl;
cout<<accumulate(v.begin(),v.end(),0);
}

## Output

Sum of all the elements are:
25
Updated on 30-Jul-2019 22:30:25