The sqrt() function is a predefined function in the <math.h> library that is used to calculate the square root of a given number. It returns the result as a double.
- Include the <math.h> header file to use the sqrt() function.
- Use sqrtf() for float values and sqrtl() for long double values.
#include <stdio.h>
#include <math.h>
int main()
{
double num = 64.0;
double result = sqrt(num);
printf("Square root of %.2lf = %.2lf", num, result);
return 0;
}
Output
Square root of 64.00 = 8.00
Syntax
double sqrt(double x);
Parameters: The sqrt() function accepts one parameter:
- x – A non-negative number whose square root is to be calculated.
Return Value: The sqrt() function returns:
- The square root of the given number as a double.
- NaN (Not a Number) if the input value is negative.
Examples
The following examples demonstrate how to use the sqrt() function in C
Example 1: Program demonstrates how we can calculate the square root of a given number using the sqrt(x) function in C.
#include <math.h>
#include <stdio.h>
int main()
{
// Declare variables to store the input number and its
// square root
double number, squareRoot;
// Prompt the user to enter a number
printf("Enter a number: ");
// Read the number entered by the user
scanf("%lf", &number);
// Compute the square root of the entered number
squareRoot = sqrt(number);
// Print the square root with 2 decimal places
printf("Square root of %.2lf = %.2lf\n", number,
squareRoot);
return 0;
}
Output
Enter a number: 25
Square root of 25.00 = 5.00Example 2: demonstrates how we can calculate square root of different data types in C.
#include <math.h>
#include <stdio.h>
int main()
{
// Declare and initialize variables of different types
// double type variable
double num1 = 9.0;
// float type variable
float num2 = 16.0f;
// long double type variable
long double num3 = 25.0l;
// Compute the square root using the appropriate sqrt
// function for each type sqrt function for double
double result1 = sqrt(num1);
// sqrtf function for float
float result2 = sqrtf(num2);
// sqrtl function for long double
long double result3 = sqrtl(num3);
// Print the results
printf("Square root of %.2f is %.2f\n", num1, result1);
printf("Square root of %.2f is %.2f\n", num2, result2);
printf("Square root of %.2Lf is %.2Lf\n", num3,
result3);
return 0;
}
Output
Square root of 9.00 is 3.00 Square root of 16.00 is 4.00 Square root of 25.00 is 5.00