This section illustrates you how to find the second largest number from an array. For this purpose, we have allowed the user to enter the array elements of their choice and determine the largest among them. Pulls the largest number out from the array and again check for the largest one i.e. for the second largest and display it.
Here is the code:
import java.util.*;
class ArrayExample {
public static void main(String[] args) {
int secondlargest = 0;
int largest = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter array values: ");
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
if (largest < arr[i]) {
secondlargest = largest;
largest = arr[i];
}
if (secondlargest < arr[i] && largest != arr[i])
secondlargest = arr[i];
}
System.out.println("Second Largest number is: " + secondlargest);
}
}
Output:
| Enter array values: 2 5 7 8 1 Second Largest number is: 7 |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.