Find Second Largest Number from an Array


 

Find Second Largest Number from an Array

This section illustrates you how to find the second largest number from an array.

This section illustrates you how to find the second largest number from an array.

Find Second Largest Number from an Array

This section illustrates you how to find the second largest number from an array. For this purpose, we have allowed the user to enter the array elements of their choice and determine the largest among them. Pulls the largest number out from the array and again check for the largest one i.e. for the second largest and display it. 

Here is the code:

import java.util.*;

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);
	}
}

Output:

Enter array values:
2
5
7
8
1
Second Largest number is: 7

Ads