Find Second Largest Element In An Array | Java Programs

Output:

*** Second Largest Number In An Array ***

Original array is: [1, 2, 4, 7, 8, 3, 5, 10]
Second largest number is : 8

Click Here For Java Online Compiler

Solution:

import java.util.Arrays;

class SecondLargestInArray {

    public static void main(String[] args) {

        int[] array = {1, 2, 4, 7, 8, 3, 5, 10};

        int max = array[0];
        int secondMax = array[0];
        System.out.println("*** Second Largest Number In An Array ***" + "\n");
        System.out.println("Original array is: " + Arrays.toString(array));

        for (int i = 0; i < array.length; i++) {

            if (array[i] > max) {
                secondMax = max;
                max = array[i];

            } else if (array[i] > secondMax) {
                secondMax = array[i];

            }
        }

        System.out.println("Second largest number is : " + secondMax);
    }
}
Share This :

Related Post

avatar

Hello, Ali! if first number will 100, result will also wrong! 100!

delete 7 September 2018 at 03:16



sentiment_satisfied Emoticon