Write a Java Program to Find Second Largest Array Number with an example. Or how to write a Java Program to find the second largest element or item in a given array.
In this Java second largest array number example, we allow the user to enter the secLrg_arr size and the array items. Next, we use the Else If statement to find the largest and the second largest event in this secLrg_arr array.
package ArrayPrograms;
import java.util.Scanner;
public class SecondLargestElement {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, first, second, lg_Position = 0;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the SEC LRG Array size : ");
Size = sc.nextInt();
int[] secLrg_arr = new int[Size];
System.out.format("\nEnter SEC LRG Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
secLrg_arr[i] = sc.nextInt();
}
first = second = Integer.MIN_VALUE;
for(i = 0; i < Size; i++)
{
if(secLrg_arr[i] > first) {
second = first;
first = secLrg_arr[i];
lg_Position = i;
}
else if(secLrg_arr[i] > second && secLrg_arr[i] < first)
{
second = secLrg_arr[i];
}
}
System.out.format("\nLargest Item in SEC LRG Array = %d", first);
System.out.format("\nLargest Item Index position = %d", lg_Position);
System.out.format("\n\nSecond Largest Item in SEC LRG Array = %d", second);
}
}
OUTPUT
Java Program to Find Second Largest Array Number example 2
In this Java code for second largest array item example, we created a separate SecondLargestElement function to find and return the second largest item in a given array.
package ArrayPrograms;
import java.util.Scanner;
public class SecondLargestElement0 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the SEC LRG Array size : ");
Size = sc.nextInt();
int[] secLrg_arr = new int[Size];
System.out.format("\nEnter SEC LRG Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
secLrg_arr[i] = sc.nextInt();
}
SecondLargestElement(secLrg_arr, Size);
}
public static void SecondLargestElement(int[] secLrg_arr, int Size) {
int i, first, second, lg_Position = 0;
first = second = Integer.MIN_VALUE;
for(i = 0; i < Size; i++)
{
if(secLrg_arr[i] > first) {
second = first;
first = secLrg_arr[i];
lg_Position = i;
}
else if(secLrg_arr[i] > second && secLrg_arr[i] < first)
{
second = secLrg_arr[i];
}
}
System.out.format("\nLargest Item in SEC LRG Array = %d", first);
System.out.format("\nLargest Item Index position = %d", lg_Position);
System.out.format("\n\nSecond Largest Item in SEC LRG Array = %d", second);
}
}
OUTPUT