Home Tutorial Java Core Find Second Largest Number from an Array

 
 

Share on Google+Share on Google+
Find Second Largest Number from an Array
Posted on: July 2, 2010 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Find Second Largest Number from an Array:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 2, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com