Wednesday, July 1, 2020

Find Second largest element in array using JAVA

Find Second largest element in an array using JAVA

PROGRAM:

public class second_largest {

    public static void main(String args[])
    {
        int a[]={ 14, 46, 47, 86, 92, 52, 48, 36, 66, 87 };
        int max=a[0];
        int second_max=a[0];
        for(int i=1;i<a.length;i++)
        {
            if(a[i]>max)
              {
                   second_max=max;
                   max=a[i];
               }
            else if(a[i]>second_max)
            {
                second_max=a[i];
            }
        }
       
        System.out.println(second_max);
    }

}

OUTPUT:
87


No comments:

Post a Comment