Javatpoint Logo
Javatpoint Logo

Array sum in c++ stl

Using accumulate in C++, we can find array sum efficiently ()

A linear data structure called an array contains identical data-type elements in a continuous stream of memory.

The sum of all the items in an array is known as array sum.

There are several ways in the C++ programming language to find the array sum.

Output:

30

Time Complexity: O(n)

Space Complexity: O(n) where n is the size of the array.

Sum of vector

Output:

30

Time Complexity: O(n)

Space Complexity: O(n) where n is the size of the array.

Classical technique

The simplest way to calculate the sum of an array's elements is to loop through them while adding 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

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++.The numeric> header file, which needs to be included at the beginning of the code in order to use this method, contains the definition for the accumulate() function:

Syntax

Example

Live Demo

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

Output:

The sum of array is 239

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 for loop from i = 0 to i = size - 1.

At every iteration of the for loop, add sum and the current element of the array, i.e., sum = sum + arr[i].

At the end of the for loop, the sum of all the elements will be stored in the sum variable.

Output:

The sum of the elements in the array: 20

Using valarray sum() function

By invoking the member function sum of the valarray class, which is used in place of the normal array, the sum operation can be performed on the valarray object directly ().







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA