17. Program to Find 2nd Largest Number in an array
💡Code:
public class SecondLargestNumber {
public static void main(String[] args) {
// Example array
int[] numbers = {15, 7, 23, 45, 9, 56, 82, 31};
// Find and print the 2nd largest number in the array
int secondLargest = findSecondLargestNumber(numbers);
System.out.println("The 2nd largest number in the array is: " + secondLargest);
}
// Function to find the 2nd largest number in an array
private static int findSecondLargestNumber(int[] array) {
if (array.length < 2) {
throw new IllegalArgumentException("Array should have at least 2 elements");
}
// Find the maximum element in the array
int max = Integer.MIN_VALUE;
for (int num : array) {
if (num > max) {
max = num;
}
}
// Find the second largest element by excluding the maximum element
int secondLargest = Integer.MIN_VALUE;
for (int num : array) {
if (num != max && num > secondLargest) {
secondLargest = num;
}
}
if (secondLargest == Integer.MIN_VALUE) {
throw new IllegalArgumentException("Array has repeated maximum elements");
}
return secondLargest;
}
}
📸Output :