AJ Java Programs
Program 5:
Finding Second Largest Element in ArrayEx: {2,3,4,5,3,1} are elements then 4 is second largest element
Syntax:
Way 1: PreDefined
import java.io.*;public class FindsecondLargest
{
public static void main(String[] args) {
// intialize the array values
int arr[] = { 1, 23, 47, 81, 92, 52, 48, 56, 66, 65 };
int largest = arr[0];
int secondLargest = arr[0];
// check the condition
for (int i = 0; i < arr.length; i++) {
// this condition check for largest number
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
// print the result
System.out.println("second largest number is:" + secondLargest);
}
}
Way 2: UserDefined
import java.io.*;public class secondLargest
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// intialize the array values
System.out.println("Enter number of elements you want to insert in array");
int n=Integer.parseInt(br.readLine());
int arr[] = new int[n+1];
System.out.println("Enter elements");
for(int j = 0;j < n; j++)
{
arr[j] = Integer.parseInt(br.readLine());
}
int largest = arr[0];
int secondLargest = arr[0];
// check the condition
for (int i = 0; i < arr.length; i++) {
// this condition check for largest number
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
// print the result
System.out.println("second largest number is:" + secondLargest);
}
}
Tested Ok Program
If You Don't Understand anything or want any program please write your request in Comment Section
And Please Like The Post
Comments
Post a Comment