Step 1:
Iterate the given array
Step 2 (first if condition arr[i] > largest):
If current array value is greater than largest value then
Move the largest value to secondLargest and make
current value as largest
Step 3 (second if condition arr[i] > secondLargest )
If the current value is smaller than largest and greater than secondLargest then
the current value becomes secondLargest
public class SecondLargest {
public static void main(String[] args) {
int arr[] = {50,06,60,70,80,90,9,150,2,35};
int largest = arr[0];
int secondLargest = arr[0];
System.out.println("The given array is:" );
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
System.out.println("\nSecond largest number is:" + secondLargest);
}
}
output :
The given array is:
50 6 60 70 80 90 9 150 2 35
Second largest number is:90