Java Program how to find second largest number in array

April 12, 2023

Program:

public class SecondLarge 
{
	public static void main(String[] args) 
	{
		int[] a = { 25, 122, 33, 45, 56 };
		int largest = a[0];
		int secondLargest = a[0];
		System.out.println("The Given Array is:");

		for (int i = 0; i < a.length; i++) 
		{
			System.out.println(a[i] + "\t");
		}

		for (int i = 0; i < a.length; i++) 
		{
			if (a[i] > largest) 
			{
				secondLargest = largest;
				largest = a[i];
			} 
			else if (a[i] > secondLargest) 
			{
				secondLargest = a[i];
			}
		}
		System.out.println("The Second Largest Number is:" + secondLargest);
	}
}

Compile:

javac SecondLarge.java
 java SecondLarge

Output:

The Given Array is:
25	
122	
33	
45	
56	
The Second Largest Number is:56

You Might Also Like