Programming Code Examples

Program to find third largest number among in an Array using Java2 min read

An example Java program to find the third largest number among five numbers:



The program starts by importing the Scanner class from the java.util package to allow the user to input numbers.

The main method declares an integer array of size 5 to store the five numbers and a Scanner object to read input from the user.

The program prompts the user to enter 5 numbers, which are stored in the nums array.

The program then declares three variables first, second, and third to store the largest, second largest, and third largest numbers, respectively. The initial values of these variables are set to the minimum value of the int type (Integer.MIN_VALUE) to ensure that any input number will be greater than these values.

The program then iterates over the nums array, comparing each number with the current values of first, second, and third. If the current number is larger than first, it becomes the new first and the old first becomes the new second, and so on. This way, the largest, second largest, and third largest numbers are updated as the loop progresses.

Finally, the program prints the value of third as the third largest number.

Add comment