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

Also Read:

Before we wrap up, let’s put your knowledge of C++ cmath sqrt() to the test! Can you solve the following challenge?

Challenge:

Write a function to find the square root of a number.

  • Return the square root of the given num.
  • For example, if num = 25, the return value should be 5.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges