Home > Back-end >  WAP to find the second largest number without using an array in java
WAP to find the second largest number without using an array in java

Time:02-13

I have received a question in my school programming assignment, which goes like this: Enter n count of numbers and find the largest and smallest among the lot. Also find the second largest number. Now, the main problem is the second smallest number part.. We have still not been taught arrays, so I want a solution to this question without arrays. This is what I have made till now, through this code, I am able to find the largest and the smallest number correctly, but I find the second smallest number part tough!

    import java.util.*;
class SecondLargest
{
    public static void main(String args[])
    {
        System.out.println('\u000C'); //used to clear screen
        Scanner y=new Scanner(System.in);
        System.out.println("Enter the number of values to be entered");
        int n=y.nextInt();
        System.out.println("Enter number 1");
        int num=y.nextInt();
        int max=num,min=num,temp=num;
        for(int i=2;i<=n;i  )
        {
            System.out.println("Enter number " i);
            num=y.nextInt();            
            if(num>max)
            max=num;
            else if(num<min)
            min=num;
            
        }
        System.out.println("The largest number is " max);
        System.out.println("The smallest number is " min);
    }
}

CodePudding user response:

Just make another variable like your min and max variables.

if (num<max && num >min) {

}

CodePudding user response:

Create additional variable max2 and shift previous max value when a new maximum is detected, or check if there is a value over max2:

Scanner y = new Scanner(System.in);
System.out.println("Enter the number of values to be entered");
int n = y.nextInt();

System.out.println("Enter number 1");
int num = y.nextInt();
int max = num, max2 = num, min = num;
    
for (int i = 2; i <= n; i  ) {
    System.out.println("Enter number "   i);
    num = y.nextInt();
    if (num < min) {
        min = num;
    } else if (num > max) {
        max2 = max; // shift previous max to become the 2nd largest
        max = num;  // store max
    } else if (num > max2) {
        max2 = num;
    }
}
System.out.println("The largest number is     "   max);
System.out.println("The 2nd largest number is "   max2);
System.out.println("The smallest number is    "   min);
  •  Tags:  
  • java
  • Related