16. Program to Find 3rd Largest Number in an array
💡Code:
public class ThirdLargestNumber7078 {
public static void main(String[] args) {
// Example array
int[] numbers = {15, 7, 23, 45, 9, 56, 82, 31};
// Find and print the 3rd largest number in the array
int thirdLargest = findThirdLargestNumber(numbers);
System.out.println("The 3rd largest number in the array is: " + thirdLargest);
}
// Function to find the 3rd largest number in an array
private static int findThirdLargestNumber(int[] array) {
if (array.length < 3) {
throw new IllegalArgumentException("Array should have at least 3 elements");
}
// Sort the array in descending order
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] < array[j]) {
// Swap elements if they are in the wrong order
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
// Return the 3rd element in the sorted array
return array[2];
}
}
📸Output :