Write a program to find the second Largest element in an array


This Java program prompts the user to enter the size of an array and its elements. It then finds and prints out the second largest element of the array. Here's how the program works:

  • The program defines a class called Array_Second_Largest.
  • Inside the class, the program defines a method called SecondSmallest that takes an array and its length as input.
  • The SecondSmallest method uses two nested for loops to sort the array in descending order.
  • The SecondSmallest method returns the second element of the sorted array, which is the second largest element.
  • The main method creates a new Scanner object to read input from the user.
  • The main method prompts the user to enter the size of the array.
  • The main method creates an array called a with the size specified by the user.
  • The main method uses a for loop to fill the array with input values from the user.
  • The main method calls the SecondSmallest method to find the second largest element in the array.
  • The main method prints out the second largest element.
  • The program ends.

Overall, this program is a simple example of how to find the second largest element in an array in Java. It is useful for beginners who are just learning how to use arrays and loops in Java.

Source Code

import java.util.Scanner;
class Array_Second_Largest
{  
	public static int SecondSmallest(int[] a, int len){  
	int t;  
	for (int i = 0; i < len; i++)   
		{  
			for (int j = i + 1; j < len; j++)   
			{  
				if (a[i] < a[j])   
				{  
					t = a[i];  
					a[i] = a[j];  
					a[j] = t;  
				}  
			}  
		}  
	   return a[1]; 
	}  
	public static void main(String args[])
	{  
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l];
        for(int i=0;i<l;i++)
        {
            System.out.printf("Element of a[%d] :",i);
            a[i]=input.nextInt();
        }
		System.out.println("Second Largest Number is : "+SecondSmallest(a,l)); 
	}
}  

Output

Enter the Array Limit :5
Element of a[0] :10
Element of a[1] :20
Element of a[2] :30
Element of a[3] :40
Element of a[4] :50
Second Largest Number is : 40

Example Programs