Array sum in c++ stlUsing 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 vectorOutput: 30 Time Complexity: O(n) Space Complexity: O(n) where n is the size of the array. Classical techniqueThe 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. AlgorithmStep 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 MethodThe 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 VectorsYou 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 loopWe 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() functionBy 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 (). |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India