Java Program to Find Second Largest Element in an Array

Java program to find second largest element in an array

import java.util.Scanner;

public class ExArraySecondLargest {
  public static void main(String[] args) {
    // intialise here.
    int n, max;

    // create object of scanner class.
    Scanner Sc = new Scanner(System.in);

    // enter total number of elements.
    System.out.print("Enter total number of elements you wants : ");
    n = Sc.nextInt();

    // creating array object.
    int a[] = new int[n];

    // enter the elements here.
    System.out.println("Enter all the elements:");
    for (int i = 0; i < n; i++) {
      a[i] = Sc.nextInt();
    }
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
        if (a[i] > a[j]) {
          max = a[i];
          a[i] = a[j];
          a[j] = max;
        }
      }
    }
    System.out.println("The Second Largest Elements in the Array is :" + a[n - 2]);
  }
}

Output

Enter total number of elements you wants : 4
Enter all the elements:
55
45
25
89
The Second Largest Elements in the Array is :55
Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment