C++ sqrt()

The sqrt() function in C++ returns the square root of a number. This function is defined in the cmath header file.

Mathematically, sqrt(x) = √x.

Example

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

int main() {
  cout << "Square root of 25 = ";
   
// print the square root of 25 cout << sqrt(25);
return 0; } // Output: Square root of 25 = 5

sqrt() Syntax

The syntax of the sqrt() function is:

sqrt(double num);

sqrt() Parameters

The sqrt() function takes the following parameter:

  • num - a non-negative number whose square root is to be computed

Note: If a negative argument is passed to sqrt(), domain error occurs.


sqrt() Return Value

The sqrt() function returns:

  • the square root of the given argument

sqrt() Prototypes

The prototypes of sqrt() as defined in the cmath header file are are:

double sqrt(double x);

float sqrt(float x);

long double sqrt(long double x);

// for integral type
double sqrt(T x);

Example 1: C++ sqrt()

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

int main() {
  double num = 10.25;
  
double result = sqrt(num);
cout << "Square root of " << num << " is " << result; return 0; }

Output

Square root of 10.25 is 3.20156

Example 2: sqrt() function With integral Argument

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

int main() {
  long num = 464453422;

double result = sqrt(num);
cout << "Square root of " << num << " is " << result; return 0; }

Output

Square root of 464453422 is 21551.2
Did you find this article helpful?