Introduction
A right-angled triangle is a type of triangle where one of the angles is exactly 90 degrees. In this type of triangle, the side opposite to the right angle is the hypotenuse, and it can be calculated using the Pythagorean theorem.
The Pythagorean theorem states that the square of the length of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the lengths of the other two sides (often referred to as the legs). This relationship is expressed as:
c² = a² + b²
Where c is the length of the hypotenuse, and a and b are the lengths of the other two sides.
The objective of this program is to calculate the length of the hypotenuse given the lengths of the two other sides of a right-angled triangle using this formula.
Code Implementation
The following C++ program calculates the length of the hypotenuse of a right-angled triangle:
#include
#include // For sqrt function
using namespace std;
int main() {
double side1, side2, hypotenuse;
// Input lengths of the two sides
cout << “Enter the length of the first side: “; cin >> side1;
cout << “Enter the length of the second side: “; cin >> side2;
// Calculate the hypotenuse using the Pythagorean theorem
hypotenuse = sqrt(pow(side1, 2) + pow(side2, 2));
// Output the result
cout << “The length of the hypotenuse is: ” << hypotenuse << endl;
return 0;
}
Program Explanation
The program is structured as follows:
- Header Files:
#include <iostream>
is included to allow input and output operations.#include <cmath>
is included for mathematical functions such assqrt
andpow
to calculate the square root and power of numbers.
- Main Function:
- The program begins execution in the
main
function. - The program prompts the user to enter the lengths of the two sides of the triangle using
cin
. - The length of the hypotenuse is calculated using the Pythagorean theorem formula:
c = sqrt(a² + b²)
, wherea
andb
are the side lengths, andsqrt
is used to calculate the square root. - The result is displayed using
cout
.
- The program begins execution in the
How to Run the Program
To run this C++ program, follow these steps:
- Save the code to a file with the .cpp extension, for example hypotenuse.cpp.
- Open a terminal or command prompt on your computer.
- Navigate to the directory where the file is saved.
- Compile the program using a C++ compiler. For example, if you are using the
g++
compiler, you can run:g++ hypotenuse.cpp -o hypotenuse
- Run the compiled program:
./hypotenuse
- Enter the lengths of the two sides when prompted, and the program will display the hypotenuse.