June 23, 2022

Find The Largest And Second Largest Element of an Array in Java

In this post we’ll see a Java program to find the largest and second largest element of an array without using any inbuilt Java method.

Steps to find the largest and second largest element of an array

  1. Declare two variables (first and second) initialized with value as lowest possible integer value.
  2. Iterate the array and compare the current array element with variable first. If element is greater than the first then assign existing value of first to second and element to first.
  3. If current array element is less than the first then also compare element with second. If element is greater than the second then assign element to second.

Largest and second largest element of an array-Java program

public class SecondLargest {
  public static void main(String[] args) {
    int arr[] = {7, 21, 45, 6, 3, 1, 9, 12, 22, 2};
    int first = Integer.MIN_VALUE;
    int second = Integer.MIN_VALUE;
    for(int i = 0; i < arr.length; i++){
      if(arr[i] > first){
        second = first;
        first = arr[i];
      }else if(arr[i] > second){
        second = arr[i];
      }			   			   
    }
    System.out.println("Largest Number = " + first + 
        " Second Largest Number = " + second);
  }
}
Output
Largest Number = 45 Second Largest Number = 22

That's all for the topic Find The Largest And Second Largest Element of an Array in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment