Skip to content
Related Articles
Open in App
Not now

Related Articles

valarray sum() in C++

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 23 Oct, 2018
Improve Article
Save Article
Like Article

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

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!