Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe for all free courses

How to use Pythagoras Theorem to calculate hypotenuse of a right-angled triangle in Java ?.

Program to demonstrate how to use Pythagoras Theorem to calculate hypotenuse of a right-angled triangle in Java

 

package com.hubberspot.code;

import java.util.Scanner;


public class PythagorasTheoremCode {

 public static void main(String[] args) {

  // In order to apply Pythagoras theorem
  // we have to apply for the formula as
  // hypotenuse * hypotenuse = height * height + base * base

  // Create a Scanner object which takes System.in object
  // this makes us read values from the console
  // We will ask user to input values for the height and base
  Scanner scanner = new Scanner(System.in);

  // Prompting user to enter height ... 
  System.out.println("Enter the height of right-angled triangle : ");
  double height = 0;
  // Scanner objects nextDouble reads output from the console
  // entered by user and stores into the double variable
  height = scanner.nextDouble();  

  // Prompting user to enter base ... 
  System.out.println("Enter the base of right-angled triangle : ");
  double base = 0;
  base = scanner.nextDouble();

  System.out.println("Applying Pythagoras Theorem  ... ");

  System.out.println();

  // Math.sqrt method calculates the square root of the argument
  // passed to it
  // Math.pow method takes two arguments and 
  // returns the value of the first argument 
  // raised to the power of the second argument.

  double hypotenuse = Math.sqrt(Math.pow(height, 2) + Math.pow(base, 2));
  System.out.println("Hypotenuse of right-angled triangle : " + hypotenuse);



 }

}



Output of the program : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot