valarray pow() Function in C++ with Examples

C++ valarray pow() Function: Here, we will learn about the pow() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on May 13, 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::pow(std::valarray) Function

The pow() function of the valarray class is used to return a valarray that contains elements that are elements raised to the power N.

Syntax:

template< class T >
std::valarray<T> pow( const std::valarray<T>& base, const std::valarray<T>& exp );

template< class T >
std::valarray<T> pow( const std::valarray<T>& base,
                      const typename std::valarray<T>::value_type& vexp );
template< class T >
std::valarray<T> pow( const typename std::valarray<T>::value_type& vbase,
                      const std::valarray<T>& exp );

// or
pow(valarrayName, N)

Parameter(s): It accepts two parameters, one the original valarray and the second one is the power to which the element is raised.

Return Value: It returns valarray with elements raised to the given power.

C++ valarray pow() Function Example 1:

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

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

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

    // Creating a new valarray of power values
    valarray<int> powValarray;
    powValarray = pow(myvalarr, 4);

    cout << "\nThe elements of power valarray are : ";
    for (int& ele : powValarray)
        cout << ele << " ";

    return 0;
}

Output:

The elements of orignal valarray are : 3 6 2 5 9 1 
The elements of power valarray are : 81 1296 16 625 6561 1 

C++ valarray pow() Function Example 2:

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

int main()
{
    // Declaring valarray
    valarray<double> myvalarr = { -3, 6.4, 0.2, -5.3, 9 };

    // Printing the elements of valarray
    cout << "The elements of orignal valarray are : ";
    for (double& ele : myvalarr)
        cout << ele << " ";

    // Creating a new valarray of power values
    valarray<double> powValarray;
    powValarray = pow(myvalarr, 3);

    cout << "\nThe elements of power valarray are : ";
    for (double& ele : powValarray)
        cout << ele << " ";

    return 0;
}

Output:

he elements of orignal valarray are : -3 6.4 0.2 -5.3 9 
The elements of power valarray are : -27 262.144 0.008 -148.877 729 




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.