Introduction
In a right-angled triangle, the hypotenuse is the side opposite the right angle and is the longest side. The length of the hypotenuse can be calculated using the Pythagorean theorem, which states that the square of the length of the hypotenuse is equal to the sum of the squares of the lengths of the other two sides.
Objective
The goal of this program is to compute the length of the hypotenuse of a right-angled triangle given the lengths of the two other sides (the perpendicular and the base). The program will utilize the Pythagorean theorem for the calculation.
C Program to Calculate the Hypotenuse of a Right-Angled Triangle
#include #include // Function to calculate the length of the hypotenuse double calculateHypotenuse(double base, double perpendicular) { return sqrt(base * base + perpendicular * perpendicular); } int main() { double base, perpendicular, hypotenuse; // Take input from the user for the base and perpendicular sides printf("Enter the length of the base: "); scanf("%lf", &base); printf("Enter the length of the perpendicular: "); scanf("%lf", &perpendicular); // Calculate the hypotenuse using the Pythagorean theorem hypotenuse = calculateHypotenuse(base, perpendicular); // Display the result printf("The length of the hypotenuse is: %.2lf\n", hypotenuse); return 0; }
Explanation of the Program
The program begins by including the necessary header files: stdio.h
for input/output operations and math.h
for mathematical functions like square root (sqrt()
).
The function calculateHypotenuse()
is defined to calculate the hypotenuse using the Pythagorean theorem: hypotenuse = sqrt(base^2 + perpendicular^2)
. It takes the values of the base and the perpendicular as inputs and returns the computed hypotenuse.
In the main()
function, the user is prompted to input the lengths of the two sides of the triangle. These values are read using the scanf()
function. Afterward, the program calls the calculateHypotenuse()
function to compute the length of the hypotenuse and then prints the result using the printf()
function.
How to Run the Program
1. Copy the program into a text editor or IDE and save the file with a .c
extension (e.g., hypotenuse.c
).
2. Compile the program using a C compiler. If you are using GCC, the command is:
gcc hypotenuse.c -o hypotenuse
3. Run the compiled program with the following command:
./hypotenuse
4. The program will prompt you to enter the lengths of the base and perpendicular sides. After input, it will output the length of the hypotenuse.