×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

valarray sqrt() Function in C++ with Examples

C++ valarray sqrt() Function: Here, we will learn about the sqrt() 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.

Mathematical sqrt value (Square root)

The square root of a number is the factor value which when multiplied by itself gives the number.

C++ STL std::sqrt(std::valarray) Function

The sqrt() function of the valarray class is used to calculate the value of the square root of elements of the valarray. It returns a valarray with each element's square root.

Syntax

template< class T >
valarray<T> sqrt( const valarray<T>& va );

// or
sqrt(valarrayName);

Parameter(s)

It accepts a single parameter which is the original valarray.

Return value

It returns a valarray with the square root value of each element of the original valarray.

Example 1

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

int main()
{
    // Declaring valarray
    valarray<int> myvalarr = { 0, 16, 729, 100, 1 };

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

    // Creating a new valarray
    valarray<int> sqrtValArray;
    sqrtValArray = sqrt(myvalarr);

    cout << "\nThe square root elements valarray are : ";
    for (int& ele : sqrtValArray)
        cout << ele << " ";

    return 0;
}

Output

The elements of orignal valarray are : 0 16 729 100 1 
The square root elements valarray are : 0 4 27 10 1

Example 2

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

int main()
{
    // Declaring valarray
    valarray<double> myvalarr = { 0, 16, 34.65, 5.76, -1 };

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

    // Creating a new valarray
    valarray<double> sqrtValArray;
    sqrtValArray = sqrt(myvalarr);

    cout << "\nThe square root elements valarray are : ";
    for (double& ele : sqrtValArray)
        cout << ele << " ";

    return 0;
}

Output

The elements of orignal valarray are : 0 16 34.65 5.76 -1 
The square root elements valarray are : 0 4 5.88643 2.4 -nan 

Note: The square root of a negative value is nan (not a number).

Comments and Discussions!

Load comments ↻





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