An example Java program to find the third largest number among five numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import java.util.Scanner; public class ThirdLargest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] nums = new int[5]; System.out.println("Enter 5 numbers:"); for (int i = 0; i < 5; i++) { nums[i] = sc.nextInt(); } int first = Integer.MIN_VALUE; int second = Integer.MIN_VALUE; int third = Integer.MIN_VALUE; for (int i = 0; i < 5; i++) { int current = nums[i]; if (current > first) { third = second; second = first; first = current; } else if (current > second) { third = second; second = current; } else if (current > third) { third = current; } } System.out.println("Third largest number is: " + third); } } |
Output:
1 2 3 4 5 | Enter 5 numbers: 10 20 30 25 35 Third largest number is: 25 |
Explanation:
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.