Java Program to Find the Greatest and Smallest of Three Numbers

In this example, we learn how to write a Java program to find the greatest and smallest of three numbers. We will write the Java program to find the greatest and smallest of three numbers. Write a Java program to input the three numbers and find the greatest and smallest from it. How to find the greatest and smallest of three numbers in java programming. Logic to find the greatest and smallest of three numbers.

Java Program to Find the Greatest and Smallest of Three Numbers

The below program ask the user to enter the three numbers. After getting the value from the user it will find the greatest and smallest number from three numbers.


import java.lang.*; 
import java.util.*;

class largesmall {

public static void main(String args[]) {
    Scanner scanner = new Scanner(System.in);
     
    System.out.println("Please enter first number :");
    int first = scanner.nextInt();  
    System.out.println("Please enter second number :");
    int second = scanner.nextInt();
    System.out.println("Please enter third number :");
    int third = scanner.nextInt();
    
    int largest = largest(first, second, third);
    int smallest = smallest(first, second, third);
    
    System.out.printf("largest of three numbers %d, %d, and %d is : %d %n", first, second, third, largest);
    System.out.printf("smallest of three numbers %d, %d, and %d is : %d %n", first, second, third, smallest);
    }

    public static int largest(int first, int second, int third) { 
        int max = first;
        if (second > max)
        { 
            max = second;
        }
        if (third > max)
        {
            max = third;
        }
    return max; 
    }

    public static int smallest(int first, int second, int third) {
        int min = first;
        if (second < min)
        {
            min = second; 
            
        } 
        if (third < min)
        {
            min = third; 
            
        }
    return min;
    }
}

Output



C:\jdk-12.0.2\bin>javac largesmall.java
C:\jdk-12.0.2\bin>java largesmall 

Please enter first number :
121
Please enter second number :
34
Please enter third number :
223

Largest of the three numbers 121, 34, 223 is: 223
Smallest of the three numbers 121, 34, 223 is: 34

No comments:

If you have any doubts, Please let me know

Powered by Blogger.