Task: Write a Program to Find Second Largest Number in Java Array. Do not use sorting. Use 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