Find Second Largest Number in Java Array

By | July 19, 2019

Task: Write a Program to Find Second Largest Number in Java Array. Do not use sorting. Use only one loop.

Find second largest number in Java array using only one loop

Find second largest number in Java array using only one loop

Java Source Code To Find Second Largest Number in Java Array

/*
 * Write a Java program to find
second largest in an array with only
ONE LOOP, that is without sorting.
 */
package secondlargest;
/**
  * @author www.EasyCodeBook.com
 */
public class SecondLargest {

    public static void main(String[] args) {
          int a[]={50,23,1,2,34},i;
          int largest1=Integer.MIN_VALUE;
          int largest2=Integer.MIN_VALUE;
          
          for(i=0;i<5;i++)
          {
              if(a[i]>largest1)
              {
                  largest2=largest1;
                  largest1=a[i];
              }
              else if (a[i]>largest2)
                  largest2=a[i];
          }
        System.out.println("Second Largest in Array="+largest2);
    }
    
}

The Output of the Java Program

Second Largest in Array=34

Leave a Reply

Your email address will not be published. Required fields are marked *