How to Find Largest Two Numbers in Array

In this example, we’ll find largest two numbers in array:

Input:
int[] arr1 = { 5, 14, 25, 29, 30 };

Output:
First Largest: 30
Second Largest: 29

1. Java

public class FindLargestTwoNumbers {

    public static void main(String[] args) {
        int arr[] = {0, 5, 18, 18, 34, 12};
        findNumbers(arr);
    }

    private static void findNumbers(int arr[]) {
        int first = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;
        for (int number : arr) {
            if (number > first) {
                second = first;
                first = number;
            } else if (number > second && number != first) {
                second = number;
            }
        }
        System.out.println("First Largest: " + first);
        if (second == Integer.MIN_VALUE) {
            System.out.println("Second Largest not found");
        } else {
            System.out.println("Second Largest: " + second);
        }
    }
}

Output:

First Largest: 34
Second Largest: 18

Complete Java Solutions can be found here: Github Link

The complete list can be found here: Practise Programming Questions

Leave a Comment