Java Program to Find the Greatest of Three Numbers

The Java program finds largest of three numbers based on the conditional statements.

Approach  :

It is required to find the largest numbers among all. The solution is quite easy and simple :

  • Check the first number whether it is greater than the second one or not
  • Similarly, check again the same number with the third one
  • If a number is greater than the rest,
  • The number would be qualified as greatest among all

C program to find greatest among three

Here’s the program to figure out which number is greatest among the three number. It would give the idea of using if and else statement.

Java program to find the greatest of three numbers using nested if-else

Program:

public class Main
{
  public static void main(String[] args) {
  int num=24,num1=20,num2=35;
    if (num > num1) {
        if (num > num2) {
    		System.out.println (num + " is Greatest "); 
        } 
        else { 
         System.out.println (num2 + " is Greatest ");
        } 
    } 
    else if (num1 > num2) { 
       	System.out.println (num1 + " is Greatest "); 
    } 
    else {
        System.out.println (num2 + " is Greatest "); 
    }
  }
}

Output:

35 is Greatest

 

Java program to find the greatest of three numbers using if-else

Program:

public class GreatestNumber {
    public static void main(String[] args) {
        int num1 = 30, num2 = 20, num3 = 40;

        if(num1 >= num2 && num1 >= num3){
            System.out.println(num1 + " is the greatest among 3");
        }
        else if(num2 >= num1 && num2 >= num3){
            System.out.println(num2 + " is the greatest among 3");
        }
        else{
            System.out.println(num3 + " is the greatest among 3");
        }
    }
}

Output: 

40 is the greatest among 3

Leave a Reply