Array sum in C++ STL


The array is a linear data structure that stores elements of the same data type in continuous memory locations.

Array sum is the sum of all elements of the array.

In C++ programming language there are multiple methods by with you can find the array sum.

Classical method

The basic method to find the sum of all elements of the array is to loop over the elements of the array and add the element’s value to the sum variable.

Algorithm

Step 1 : For i from 0 to n-1, follow step 2 ;
Step 2 : sum = sum + arr[i]
Step 3 : print sum.

Example

 Live Demo

#include <iostream>
using namespace std;
int main (){
   int arr[] = { 2, 5, 7, 8, 2, 6, 9 };
   int n = 7, sum = 0;
   for(int i = 0; i<n ; i++){
      sum+=arr[i];
   }
   cout<<"The array sum is "<<sum;
   return 0;
}

Output

The array sum is 39

Using Accumulate Method

The accumulate() method in C++ used to find the array sum. This function can be accessed from the numeric library in C++.

Syntax

accumulate(array_name , array_name+length , sum);

Example

 Live Demo

#include <iostream>
#include <numeric>
using namespace std;
int main (){
   int arr[] = { 2, 5, 7, 8, 2, 6, 9 };
   int n = 7, sum = 0;
   sum = accumulate(arr, arr+n, sum);
   cout<<"The array sum is "<<sum;
   return 0;
}

Output

The array sum is 39

Using Sum Of Vectors

You can use the accumulate() function on vectors too. It will return the sum of array which is it vector form.

Example

 Live Demo

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int arraySum(vector<int> &v){
   int initial_sum = 0;
   return accumulate(v.begin(), v.end(), initial_sum);
}
int main(){
   vector<int> v{12, 56, 76, 2, 90 , 3} ;
   int sum = 0;
   sum=accumulate(v.begin(), v.end(), sum);
   cout<<"The sum of array is "<<sum;
   return 0;
}

Output

The sum of array is 239

Updated on: 14-Sep-2023

27K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements