In this C++ tutorial, you will learn how to find square root of sum of square of given numbers using hypot() function of cmath, with syntax and examples.

C++ hypot()

C++ hypot() returns square root of sum of square of given arguments.

This formula is used for finding the length of hypotenuse when the lengths of other two sides of a right angled triangle are given. Hence, the function name hypot().

Syntax

The syntax of C++ hypot() is

</>
Copy
hypot(x, y)

where

ParameterDescription
xA double, float, long double, or integral type value.
yA double, float, long double, or integral type value.

Returns

The return value depends on the type of value passed for parameter x.

The return value of hypot(x) is

  • double if x and y are double.
  • float if x and y are float.
  • long double if x and y are long double.
  • Promoted datatype if x and y are of different integral datatypes.

The synopsis of hypot() function is

</>
Copy
double hypot(double x, double y);
float hypot(float x, float y);
long double hypot(long double x, long double y);
Promoted hypot(Type1 x, Type2 y); // for combinations of other numeric types

Since C++17, hypot() can accept another value for third argument. The definition of return value remains same.

</>
Copy
double hypot(double x, double y, double z);
float hypot(float x, float y, float z);
long double hypot(long double x, long double y, long double z);
Promoted hypot(Type1 x, Type2 y, Type3 z); // for combinations of other numeric types

sinh() is a function of cmath library. Include cmath library at the start of program, if using hypot() function.

Example

1. hypot(x, y)

In this example, we read two values from user into variables x and y, and compute the hypotenuse using hypot() function.

C++ Program

</>
Copy
#include <iostream>
#include<cmath>
using namespace std;

int main() {
    double x, y;
    cout << "Enter a value (x) : ";
    cin >> x;
    cout << "Enter a value (y) : ";
    cin >> y;
    
    double result = hypot(x, y);
    cout << "hypot(" << x << ", " << y << ") : " << result << endl;
}

Output

Enter a value (x) : 3
Enter a value (y) : 4
hypot(3, 4) : 5
Program ended with exit code: 0
Enter a value (x) : 6
Enter a value (y) : 2
hypot(6, 2) : 6.32456
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ hypot(), and how to use this function to find the hypotenuse value when two sides are given, with the help of examples.