Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Here’s my code snippet: 

public static void main(String[] args) {

    int num;

    int large;

    int small;

    int secondLarge;

 

    Scanner scan = new Scanner(System.in);

    System.out.print("Input a number: ");

    num = scan.nextInt();

    large = num;

    small = num;

    secondLarge = num;

 

    for (int x = 9; x > 0; x--) {

        System.out.print("Enter " + x + " more number: ");

        num = scan.nextInt();

 

        if (num > large) {

            large = num;

 

        }

        if (num > secondLarge) {

            secondLarge = num;

        }

 

        if (secondLarge > large) {

            large = secondLarge;

}

        if (num < small) {

            small = num;

}

       } 

       System.out.println( large + " is the largest number, " + secondLarge + " is the second largest number and " + small + " is the smallest number!");

}

It correctly prints the smallest and largest number. But it fails when I want to print the second-largest number. 

How to find the second largest element in the for loop? 

1 Answer

0 votes
by (19.7k points)

Here’s the initialization of variables :

int large=0;

int secondLarge=0;

int small=Integer.MAX_VALUE;

Use the condition below:

if(num>=large){

    secondLarge=large;

    large=num;

}else if(num>secondLarge){

    secondLarge=num;

}

if(num<small){

    small=num;

}

Related questions

Browse Categories

...