Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Conditional Constructs in Java

Chapter 9

Conditional Constructs in Java

Class 9 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Programs - Check Pythagorean Triplet


Write a program in Java to accept three numbers and check whether they are Pythagorean Triplet or not. The program must display the message accordingly. [Hint: h2=p2+b2]

import java.util.Scanner;

 

public class PythagoreanTriplet {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter first number: ");

        int a = sc.nextInt();

 

        System.out.print("Enter second number: ");

        int b = sc.nextInt();

 

        System.out.print("Enter third number: ");

        int c = sc.nextInt();

 

        int h, p, base;

 

        // Find the largest number (hypotenuse)

        if (a >= b && a >= c) {

            h = a;

            p = b;

            base = c;

        } else if (b >= a && b >= c) {

            h = b;

            p = a;

            base = c;

        } else {

            h = c;

            p = a;

            base = b;

        }

 

        // Check Pythagorean condition

        if ((h * h) == (p * p + base * base)) {

            System.out.println("The numbers form a Pythagorean Triplet.");

        } else {

            System.out.println("The numbers do NOT form a Pythagorean Triplet.");

        }

 

        sc.close();

    }

}

Output

Output 1 :

SAMPLE INPUT : Enter first number: 3 Enter second number: 4 Enter third number: 5 SAMPLE OUTPUT : The numbers form a Pythagorean Triplet.

Output 2 :

SAMPLE INPUT : Enter first number: 6 Enter second number: 8 Enter third number: 10 SAMPLE OUTPUT : The numbers form a Pythagorean Triplet.

Output 3 :

SAMPLE INPUT : Enter first number: 2 Enter second number: 3 Enter third number: 4 SAMPLE OUTPUT : The numbers do NOT form a Pythagorean Triplet.

Explanation

1. Input Three Numbers

  • Accepts three integers from the user.

2. Identify the Hypotenuse

  • The largest number is taken as the hypotenuse (h).

3. Apply Pythagorean Formula

                             h2 = p2 + b2

         if ((h * h) == (p * p + base * base))

4. Display Result

  • Prints whether the numbers form a Pythagorean Triplet or not.