Array Sum In C++ STL - C++ Programming Tutorial
C++ Course / STL Basics / Array Sum In C++ STL

Array Sum In C++ STL

BLUF: Mastering Array Sum In C++ STL is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Array Sum In C++ STL

C++ is renowned for its efficiency. Learn how Array Sum In C++ STL enables low-level control and high-performance computing in the tutorial below.

By utilizing the accumulate function in C++, we can efficiently calculate the sum of an array.

A sequential data structure known as an array stores elements of the same data type consecutively in a contiguous block of memory.

The total of all elements within an array is referred to as the array sum.

There exist multiple methods in the C++ programming language for calculating the sum of an array.

Example

// C++ program to demonstrate working of accumulate()
#include <iostream>
#include <numeric>

using namespace std;

// User defined function that returns sum of
// arr[] using accumulate() library function.
int arraySum(int a[], int n)
{
	int initial_sum = 0;
	return accumulate(a, a+n, initial_sum);
}

int main()
{
	int a[] = {5 , 10 , 15} ;
	int n = sizeof(a)/sizeof(a[0]);
	cout << arraySum(a, n);
	return 0;
}

Output:

Time Complexity: O(n)

Space Complexity: O(n) denoting the array's size as 'n'.

Sum of vector

Example

// C++ program to demonstrate working of accumulate()
#include <iostream>
#include <vector>

#include <numeric>
using namespace std;

// User defined function that returns sum of
// arr[] using accumulate() library function.
int arraySum(vector<int> &v)
{
	int initial_sum = 0;
	return accumulate(v.begin(), v.end(), initial_sum);
}

int main()
{
	vector<int> v{5 , 10 , 15} ;
	cout << arraySum(v);
	return 0;
}

Output:

Time Complexity: O(n)

Space Complexity: O(n) denotes that the amount of space required by the algorithm grows linearly with the size of the array, represented by 'n'.

Classical technique

A straightforward method to compute the total of an array's elements involves iterating through each element and incrementing the sum variable by the element's value.

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

Example

#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:

Output

The array sum is 39

Using Accumulate Method

The accumulate function in C++ is employed to calculate the total of elements in an array. This functionality is accessible within the numeric library in C++. To utilize this function, the code must include the numeric> header file at the start, as it houses the implementation for the accumulate function:

Syntax

Example

accumulate(array_name , array_name+length , sum);

Example

Live Demo

Example

#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:

Output

The array sum is 39

Using Sum Of Vectors

You can also apply the accumulate function to vectors. This function will provide the total sum of the array represented in vector form.

Example

Live Demo

Example

#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:

Output

The sum of array is 239

Use a for loop

We can employ a for loop to iterate through the array. Each element can be accumulated sequentially:

Initialize sum = 0.

Run a for loop from i = 0 to i = size - 1.

At each iteration of the for loop, calculate the sum by adding the current array element, such as sum = sum + arr[i].

Upon completion of the for loop, the cumulative total of all elements will be saved in the sum variable.

Example

#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;
}

Output:

Output

The sum of the elements in the array: 20

Using valarray sum function

By calling the sum member function of the valarray class, which serves as a replacement for the traditional array, you can execute the sum operation directly on the valarray object.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience