ADVERTISEMENT
ADVERTISEMENT

valarray sum() Function in C++ with Examples

C++ valarray sum() Function: Here, we will learn about the sum() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on May 08, 2022

The valarray class in C++ is a special container that is used for holding elements like an array and performing operations on them.

std::valarray<T>::sum() Function

The sum() function is defined in valarray class, and it returns the sum of all the elements of 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;

// or
valarray.sum()

Parameter(s): The method does not require any parameter.

Return Value: The method returns a single value with the same type as the element of the valarray.

C++ valarray sum() Function Example 1:

#include <iostream>
#include <valarray>
using namespace std;

int main()
{
    // Declaring valarray
    valarray<int> myvalarr = { 1, 2, 3, 4, 5, 6, 7 };

    // Printing the elements of valarray
    cout << "The elements stored in valarray are : ";
    for (int& ele : myvalarr)
        cout << ele << " ";

    // Calculating the sum of all elements of valarray
    cout << "\nThe sum of all elements of valarray is ";
    cout << myvalarr.sum();
    
    return 0;
}

Output:

The elements stored in valarray are : 1 2 3 4 5 6 7 
The sum of all elements of valarray is 28

C++ valarray sum() Function Example 2:

// Program to find the type of summed value

#include <iostream>
#include <valarray>
#include <typeinfo>
using namespace std;

int main()
{
    // Declaring valarray
    valarray<float> myvalarr = { 1, 2, 3, 4, 5, 6, 7.4 };

    // Printing the elements of valarray
    cout << "The elements stored in valarray are : ";
    for (float& ele : myvalarr)
        cout << ele << " ";

    // Calculating the sum of all elements of valarray
    cout << "\nThe type of summed values is ";
    cout << typeid(myvalarr.sum()).name();
    
    return 0;
}

Output:

The elements stored in valarray are : 1 2 3 4 5 6 7.4 
The type of summed values is f

ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.