Java Program to find the greatest of three Numbers

In this post, we will write two java programs to find the largest among three numbers.

1)Using if-else

2) Using nested If-else

Input three number from user and compare these number with each other and find largest number among these three numbers. Here we are using ternary operator for find largest number.

How the program will work?

Nested if-else

  • If num1 is greater or equal to both num2 and num3, n1 is the greatest.
  • If num2 is greater or equal to both num1 and num3, n2 is the greatest.
  • Else, num2 is greatest.

Nested if-else

  • If num1 is greater or equals to num2,
    • and if num1 is greater or equals to num3, num1 is the greatest.
    • Else, num3 is the greatest.
  • Else,
    • if num2 is greater or equal to both num3, num2 is the greatest.
    • Else, num3 is the greatest.

Lets write this logic in Java Program.

Example:

if (num1>num2) and (num1>num3)
Print num1
Else if (num2>num1) and (num2>num3)
Print num2
else
Print num3

Example 1: Program Finding largest of three number using Nest if-else

import java.util.Scanner;
public class compare_three_number {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        int num3 = sc.nextInt();

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

Example 2: Program Finding largest of three number using if-else statement

import java.util.Scanner;
public class compare_three_number {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        int num3 = sc.nextInt();

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

Recommended:

  1. Java Program to solve quadratic equations
  2. Check if the given number is prime or not in Java
  3. Java Program Count invalid Mobile numbers form list
  4. Java program Fill a bucket with water using a mug
  5. Java Program to Check if Number is Positive or Negative
  6.  

Leave a Comment

Your email address will not be published. Required fields are marked *

x