The hypot() function in C is used to find the length of the hypotenuse of a right-angled triangle given the lengths of the other two sides. This function is particularly useful in various fields of science and engineering where distance calculations are required.
The function is declared in the <math.h> header file.
Syntax of hypot() in Cdouble hypot(double x, double y); ParametersThe hypot(x, y) function takes two parameters:
- x: A variable of type double representing one side of the right-angled triangle.
- y: A variable of type double representing the other side of the right-angled triangle.
Return ValueThe hypot(x, y) function returns the hypotenuse of a right-angled triangle with sides x and y. The result is a double value that represents the length of the hypotenuse. This function avoids overflow and underflow that might occur with direct computation of the square root of the sum of the squares of x and y.
Example of hypot() in CThe below program illustrates how to calculate the hypotenuse of a right-angled triangle using the hypot(x, y) function in C:
C++
// C Program to calculate the hypotenuse of a right-angled triangle using
// hypot() function
#include <math.h>
#include <stdio.h>
int main()
{
// Initialize variables to take the input from the user
// and store the results
double x, y, hypotenuse;
// Take the input from the user
printf("Enter the lengths of the two sides of the right-angled triangle:\n");
// Read the lengths entered by the user
scanf("%lf %lf", &x, &y);
// Calculate the hypotenuse of the right-angled triangle
hypotenuse = hypot(x, y);
// Print the hypotenuse
printf("The hypotenuse of the triangle with sides %.2lf and %.2lf is: %.2lf\n", x, y, hypotenuse);
return 0;
}
Output
Enter the lengths of the two sides of the right-angled triangle: 3 4 The hypotenuse of the triangle with sides 3.00 and 4.00 is: 5.00 Time Complexity: O(1) Auxiliary Space: O(1)
Advantages of Using hypot() - Numerical Stability: The
hypot() function handles large and small values of x and y better than a straightforward calculation of the square root of the sum of the squares. - Overflow and Underflow Protection: By using internal scaling,
hypot() avoids intermediate overflow and underflow during the computation, which makes it more robust for a wide range of inputs. - Simplicity: It provides a simple and direct way to compute the hypotenuse without needing to manually perform the intermediate steps.
|