Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
math
communitycreator

# How to find the sum of values in an array in C++

Sarah Tanveer

In this shot, we will go over how to sum up all the values in a one-dimensional array.

Example of what the algorithm will do

There are two main ways to achieve this, as discussed below.

## 1. Use a for loop

We can use a for loop to traverse the array. All the elements can be added up one by one:

1. Initialize sum = 0.
2. Run a for loop from i = 0 to i = size - 1.
3. At every iteration of the for loop, add sum and the current element of the array, i.e., sum = sum + arr[i].
4. At the end of the for loop, the sum of all the elements will be stored in the sum variable.

### Dry run of for loop

First iteration of for loop
1 of 5
#include <iostream>
using namespace std;

int main() {
// initialise array
int arr[] = {2, 4, 6, 8};
int size = 4;

// initialise sum to zero
int sum = 0;

// for loop runs from 0 to size - 1
for(int i = 0; i < size; i++)
{
sum = sum + arr[i];
}

cout << "The sum of the elements in the array: " << sum;
}

## 2. Use the accumulate() function

The accumulate() function is defined in the <numeric> header file, which must be included at the start of the code in order to access this function:

accumulate(arr , arr+size , sum);


The function takes three arguments:

1. arr: The name of the array.
2. arr+size: The name of the array + size of the array.
3. sum: The variable in which the sum needs to be stored.

The function returns an int value, which is the sum of all the elements in the array.

#include <iostream>
#include<numeric>
using namespace std;

int main() {
// initialise array
int arr[] = {2, 4, 6, 8};
int size = 4;

// initialise sum to zero
int sum = 0;

// use function
sum = accumulate(arr, arr+size, sum);

cout << "The sum of the elements in the array: " << sum;
}

RELATED TAGS

c++
math
communitycreator

CONTRIBUTOR

Sarah Tanveer
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time