Open In App

valarray sum() in C++

Last Updated : 23 Oct, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads