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:
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.
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)); } }
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
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions