Dipu Dipu - 2 months ago 5
Java Question

Display Second Largest no in Array in Java

Hi all I want to find out second Largest no in Array accept negative numbers. I have used following code and this display second largest no of only positive no.So please suggest me how to do this.

class ArrayExample {
public static void main(String[] args) {
int secondlargest = 0;
int largest = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
}
System.out.println("Second Largest number is: " + secondlargest);
}
}

Answer

Initialize the variables secondlargest and largest with the smallest negative values.
Use this code:

class ArrayExample {
        public static void main(String[] args) {
            int secondlargest = Integer.MIN_VALUE;
            int largest = Integer.MIN_VALUE;
            Scanner input = new Scanner(System.in);
            System.out.println("Enter array values: ");
            int arr[] = new int[5];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = input.nextInt();
                if (largest < arr[i]) {
                    secondlargest = largest;
                    largest = arr[i];
                }
                if (secondlargest < arr[i] && largest != arr[i])
                    secondlargest = arr[i];
            }
            System.out.println("Second Largest number is: " + secondlargest);
        }
    }
Comments