sqrt() function in C is a predefined function in the math.h library used to calculate the square root of a given number. To use this function, we must include the <math.h> header file in our program. It returns the square root of the number as a double and works with double data types, for other data types like float or long double, we can use sqrtf() and sqrtl(), respectively.
Syntax of sqrt() in C
double sqrt(double x);Parameters of sqrt()
The sqrt(x) function takes a single parameter:
- x: A non-negative double value for which the square root is to be calculated that must be a non-negative double.
Return Value of sqrt()
The sqrt(x) function returns the square root of the given number x passed as parameter. If the input is negative, it returns a domain error (NaN) because square root of negative number results in a imaginary number that is not supported by sqrt() function.
Examples of sqrt() in C
Input:
double number = 25.0;
Output:
Square root of 25.00 = 5.00
Example 1
The below program demonstrates how we can calculate the square root of a given number using the sqrt(x) function in C.
// C Program to calculate the square root using sqrt()
// function
#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.00
Time Complexity: O(1), constant as it performs a single mathematical operation.
Auxiliary Space: O(1)
Example 2
The below example demonstrates how we can calculate square root of different data types in C.
// C program to calculate square root of different data
// types
#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
Time Complexity: O(1)
Auxiliary Space: O(1)