Go to Top

Sunday, 2 October 2011

To find the second highest number

Question 51 : Write a program in Java to find the second highest number from a list of numbers taken as input from the user (w/o using array). The list terminates when the user enters 0.

Java Program :

import java.io.*;
class sec_high
{
 static void high()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int max=0,sec=0,n=0,i,last=0;
     System.out.print("Enter the numbers one by one and 0 to exit");
     System.out.print("Enter number : ");
     max=Integer.parseInt(br.readLine());
     System.out.print("\nEnter number : ");
     sec=Integer.parseInt(br.readLine());
     if(sec>max)
    {
     last=sec;
     sec=max;
     max=last;
    }
   do
   {
         System.out.print("\nEnter number : ");
         i=Integer.parseInt(br.readLine());
         if(i!=0)
         n=i;
         if(n<max && n<sec)
         continue;
         else if(n>max)
         {
             sec=max;
             max=n;
            }
            else if(n<max && n>sec)
            sec=n;
        }while(i!=0);
        System.out.print("\nHighest number : "+max);
        System.out.print("\n\nSecond highest number : "+sec);
    }
}

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Discovering the second highest number demands a keen analytical eye. Fix Slow Streaming It involves comparing values systematically to extract the runner-up.

    ReplyDelete

ShareThis