Cover Image for Square Root in C
107 views

Square Root in C

You can calculate the square root of a number using the sqrt() function, which is part of the math library (math.h). The sqrt() function takes a single argument, which is the number for which you want to calculate the square root, and it returns the square root as a double value.

Here’s the prototype of the sqrt() function:

C
#include <math.h>

double sqrt(double x);
  • x: The number for which you want to calculate the square root. It should be a non-negative value (zero or positive).

Here’s an example of how to use the sqrt() function:

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

int main() {
    double number = 25.0;  // The number for which we want to find the square root
    double result = sqrt(number);

    printf("The square root of %.2f is %.2f\n", number, result);

    return 0;
}

In this example, we use the sqrt() function to calculate the square root of the number 25.0, and the result is 5.00.

It’s important to note that the sqrt() function returns a double value. If you want to use the square root as an integer, you can cast the result to an integer type like this:

C
int integerResult = (int)sqrt(number);

Keep in mind that the sqrt() function is designed for non-negative numbers. If you attempt to calculate the square root of a negative number, it will result in a “domain error,” and you may want to handle such cases accordingly in your program.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS