Skip to content
Related Articles

Related Articles

Improve Article

valarray sum() in C++

  • Difficulty Level : Basic
  • Last Updated : 23 Oct, 2018
Geek Week

The sum() function is defined in valarray header file. This function returns the sum of all the elements in the valarray, as if calculated by applying operator+= to a copy of one element and all the other elements, in an unspecified order.

Syntax:

T sum() const;

Returns: This function returns the sum of all the elements in the valarray.

Below programs illustrate the above function:

Example 1:-






// C++ program to demonstrate
// example of sum() function.
  
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // Initializing valarray
    valarray<int> varr = { 15, 10, 30, 33, 40 };
  
    // Displaying sum of valarray
    cout << "The sum of valarray is = "
         << varr.sum() << endl;
  
    return 0;
}
Output:
The sum of valarray is = 128

Example 2:-




// C++ program to demonstrate
// example of sum() function.
  
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // Initializing valarray
    valarray<int> varr = { 1, 2, 3, 4, 5 };
  
    // Displaying sum of valarray
    cout << "The sum of valarray is = "
         << varr.sum() << endl;
  
    return 0;
}
Output:
The sum of valarray is = 15
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :