write a java program to find second largest element in an Array?

We can find the second largest element in an array by iterating the array from for the loop and comparing second largest with largest value.

				
					public class SecongLargestNummber {
	public static void main(String[] args) {
		int arr[] = { 100, 14, 46, 47, 94, 94, 52, 86, 36, 94, 89 };
		int largest = 0;
		int secondLargest = 0;
		for (int i = 0; i < arr.length; i++) {
			if (largest < arr[i]) {
				secondLargest = largest;
				largest = arr[i];
			} else if (arr[i] > secondLargest) {
				secondLargest = arr[i];
			}
		}
		System.out.println("second largset number: " + secondLargest);
	}
}
				
			

Output :-
second largest number: 94

Leave a Comment

Your email address will not be published. Required fields are marked *