Java Program to Calculate the Length of Hypotenuse

In the previous article, we have seen Java Program for Triangular Matchstick Number

In this article we are going to see how to calculate the length of hypotenuse using Java programming language.

Java Program to Calculate the Length of Hypotenuse

Before Jumping into the program directly let’s see how we can calculate the length of hypotenuse.

Explanation:

The longest side of a right angled triangle is called as the hypotenuse.

According to Pythagoras theorem:

H2  = P2 + B2

H =  sqrt(P2 + B2)

Where, H = hypotenuse, P = perpendicular side of the triangle, B = base of the triangle

Example:

Let P = 3

B = 4

H2  = P2 + B2

H =  sqrt((P*P) + (B*B)) = sqrt(9 + 16) = sqrt(25) = 5

Let’s see different ways to find the length of hypotenuse.

Method-1: Java Program to Calculate the Length of Hypotenuse By Using Static Value

Approach:

  • Declare a double variable say ‘p’ and assign the value to it, which holds the value of the length of the perpendicular side.
  • Declare a double variable say ‘b’ and assign the value to it, which holds the value of the length of the base.
  • Find the hypotenuse of the right angled triangle using the formula sqrt((P*P) + (B*B))
  • Print the result.

Program:

import java.io.*;
class Main
{
    public static void main(String [] args)
    {
        double p = 3;
        double b = 4;   
        // formula to find hypotenuse 
        double h =  Math.sqrt((p*p)+(b*b)); 
        System.out.println("The hypotenuse is: " + h);
    }
}

Output:

The hypotenuse is: 5.0

Method-2: Java Program to Calculate the Length of Hypotenuse By Using User Input Value

Approach:

  • Declare a double variable say ‘p’ and take the value as user input, it is the length of the perpendicular side.
  • Declare a double variable say ‘b’ and take the value as user input, it is the length of the base.
  • Find the hypotenuse of the right angled triangle using the formula sqrt((P*P) + (B*B))
  • Print the result.

Program:

import java.io.*;
import java.util.Scanner;
class Main
{
    public static void main(String [] args)
    {
        // Scanner class object created
        Scanner s = new Scanner(System.in);                        
        System.out.println("Enter the value of perpendicular side:");
        double p = s.nextDouble();                                          
        System.out.println("Enter the value of base:");
        double b =  s.nextDouble();             
        // formula to find hypotenuse
        double h = Math.sqrt((p*p)+(b*b));                    
        System.out.println("The hypotenuse is:" + h);
    }
}

Output:

Enter the value of perpendicular side:
4
Enter the value of base:
5
The hypotenuse is:6.4031242374328485

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Related Java Programs: