How to find the sum of values in an array in C++
In this Answer, we will go over how to sum up all the values in a one-dimensional array.
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:
- Initialize
sum = 0. - Run a
forloop fromi = 0toi = size - 1. - At every iteration of the
forloop, addsumand the current element of the array, i.e.,sum = sum + arr[i]. - At the end of the
forloop, the sum of all the elements will be stored in thesumvariable.
Dry run of for loop
First iteration of for loop
1 of 4
#include <iostream>using namespace std;int main() {// initialise arrayint arr[] = {2, 4, 6, 8};int size = 4;// initialise sum to zeroint sum = 0;// for loop runs from 0 to size - 1for(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:
arr: The name of the array.arr+size: The name of the array + size of the array.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 arrayint arr[] = {2, 4, 6, 8};int size = 4;// initialise sum to zeroint sum = 0;// use functionsum = accumulate(arr, arr+size, sum);cout << "The sum of the elements in the array: " << sum;}