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.
for
loopWe can use a for
loop to traverse the array. All the elements can be added up one by one:
sum = 0
.for
loop from i = 0
to i = size - 1
.for
loop, add sum
and the current element of the array, i.e., sum = sum + arr[i]
.for
loop, the sum of all the elements will be stored in the sum
variable.for
loop#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;}
accumulate()
functionThe 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;}