Java Program to find the second largest number in an array


In this program, You will learn how to find the second largest number in an array in java.


List is: 1 2 3 4 5

The second-largest number is: 4

Example: How to find the second largest number in an array in java.

import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        Scanner s = new Scanner(System.in);
        int a[] = new int[100];
        int n, largest = 0, slargest = -1;

        System.out.print("Enter size of an array:");
        n = s.nextInt();

        System.out.print("Enter array elements:");

        for (int i = 0; i < n; i++) {
            a[i] = s.nextInt();
        }
        for (int i = 0; i < n; i++) {
            if (largest <= a[i]) {
                largest = a[i];
            }
        }

        for (int i = 0; i < n; i++) {
            if (slargest <= a[i] && a[i] < largest) {
                slargest = a[i];
            }
        }

        System.out.print("Second Largest number:" + slargest);
    }
}

Output:

Enter size of an array:5
Enter array elements:20 30 40 50 10
Second Largest number:40

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.