Java Programs for freshers: Find second largest number in the array

               In this series of programming, let us create a java program to find the largest number in the array.

Logic:

  • Get the number of elements in the array.
  • Read the array elements from the user.
  • Find the largest value and the minimum value in the array.
  • Create a for loop for checking all elements.
  • Now, check the element is greater than largest value, then assign the element as largest value.
  • Else, if the element is greater than second largest and not equal to largest, assign it as second largest.
  • If the second largest is equal to minimum value, then print there is no second largest number.
  • Otherwise, print the second largest number.

Program implementation:

  • Include the built in package.
  • Create a public class with main() function.
  • Using scanner object,read the number of elements and elements from the user at run time.
  • Use the above logic to implement the program.

Program:

import java.util.Scanner;

public class SecondLargestEg {

    public static void main(String[] args) {

        Scanner sObj = new Scanner(System.in);

              System.out.print("Enter the number of elements of the array: ");

              int n = sObj.nextInt();

        int[] a = new int[n];

              System.out.println("Enter the elements of the array: ");

              for (int i = 0; i < n; i++) {

              a[i] = sObj.nextInt();

              }

        int large = Integer.MIN_VALUE;

        int secondLarge = Integer.MIN_VALUE;

        for (int i = 0; i < a.length; i++) {

            if (a[i] > large) {

                secondLarge = large;

                large = a[i];

            } else if (a[i] > secondLarge && a[i] != large) {

                secondLarge = a[i];

            }

        }

       

        if (secondLarge == Integer.MIN_VALUE) {

            System.out.println("There is no second largest number.");

        } else {

            System.out.println("The second largest number is: " + secondLarge);

        }

    }

}

Output:

C:\raji\blog>javac SecondLargestEg.java

C:\raji\blog>java SecondLargestEg

Enter the number of elements of the array: 5

Enter the elements of the array:

235

312

657

456

888

The second largest number is: 657

This is the way of implementing java program to find the second largest number in the array.

No comments:

Post a Comment