C library - sqrt() function



The C library sqrt() function of type double accept the variable x(double) as parameter to return the result of square root. The square of a number is obtained by multiplying the number by itself.

Syntax

Following is the syntax of the C library function sqrt()

double sqrt(double x)

Parameters

This function accepts only a single parameters −

  • x − This is the floating point value.

Return Value

This function returns the square root of x.

Example 1

Following is the C library program that illustrates the usage of sqrt() function.

#include <stdio.h>
#include <math.h>

int main () {

   printf("Square root of %lf is %lf\n", 4.0, sqrt(4.0) );
   printf("Square root of %lf is %lf\n", 5.0, sqrt(5.0) );
   
   return(0);
}

Output

On execution of above code, we get the following result −

Square root of 4.000000 is 2.000000
Square root of 5.000000 is 2.236068

Example 2

Below the example demonstrate the usage of sqrt() function in a loop. This program involve the table of square roots ranges between 0-10.

#include <stdio.h>
#include <math.h>

int main() {
   // Generate square roots for numbers 0 to 10
   int maxNumber = 10; 

   printf("Table of Square Roots:\n");
   for (int i = 0; i <= maxNumber; ++i) {
       double result = sqrt(i);
       printf("sqrt(%d) = %.2lf\n", i, result);
   }

   return 0;
}

Output

After executing the above code, we get the following result −

Table of Square Roots:
sqrt(0) = 0.00
sqrt(1) = 1.00
sqrt(2) = 1.41
sqrt(3) = 1.73
sqrt(4) = 2.00
sqrt(5) = 2.24
sqrt(6) = 2.45
sqrt(7) = 2.65
sqrt(8) = 2.83
sqrt(9) = 3.00
sqrt(10) = 3.16

Example 3

In this example, we are finding the square root of a real number.

#include <stdio.h>
#include <math.h>

int main() {
   double number, squareRoot;
   printf("Enter a number: ");
   scanf("%lf", &number);

   // Compute the square root
   squareRoot = sqrt(number);

   printf("Square root of %.2lf = %.2lf\n", number, squareRoot);
   return 0;
}

Output

The above code produces the following result −

Enter a number: 4
Square root of 4.00 = 2.00
Advertisements