Write a program to display the largest and smallest numbers


This Java program reads input from the user and finds the largest and smallest numbers among them. It repeatedly prompts the user to enter a number and asks if they want to continue. It keeps track of the largest and smallest numbers using the variables max and min, which are initially set to the minimum and maximum possible integer values, respectively.

Here is a step-by-step explanation of how the program works:

  • The program starts by creating a Scanner object to read input from the user.
  • It declares three integer variables: number, max, and min. number will be used to store the number entered by the user, while max and min will be used to keep track of the largest and smallest numbers seen so far. max is initialized to Integer.MIN_VALUE, which is the smallest possible integer value, and min is initialized to Integer.MAX_VALUE, which is the largest possible integer value.
  • The program enters a do-while loop that prompts the user to enter a number, reads the number using input.nextInt(), and stores it in the number variable.
  • If the number is greater than max, it becomes the new max. If it is less than min, it becomes the new min.
  • The program then prompts the user to enter a choice whether to continue or not. The input.next().charAt(0) method reads the first character of the user's input, which is assumed to be either 'y' or 'n'.
  • The loop continues as long as the user enters 'y' or 'Y'.
  • When the loop terminates, the program prints the largest and smallest numbers found using the System.out.println() method.

Source Code

import java.util.Scanner;
class Display_Largest_Smallest{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);        
        int number;
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        char choice;	
        do
        {
            System.out.print("Enter the Number :");
            number = input.nextInt();        
            if(number > max)
            {
                max = number;
            }            
            if(number < min)
            {
                min = number;
            }        
            System.out.print("Do you want to Continue y/n ? :");
            choice = input.next().charAt(0);
 
        }while(choice=='y' || choice == 'Y');
 
        System.out.println("Largest Number : " + max);
        System.out.println("Smallest Number : " + min);
    }  
}

Output

Enter the Number :34
Do you want to Continue y/n ? :y
Enter the Number :78
Do you want to Continue y/n ? :y
Enter the Number :12
Do you want to Continue y/n ? :n
Largest Number : 78
Smallest Number : 12

Example Programs