-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecondLargestInArr.java
More file actions
24 lines (24 loc) · 897 Bytes
/
Copy pathsecondLargestInArr.java
File metadata and controls
24 lines (24 loc) · 897 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package arrays;
//Question: Find the second largest element of an array.
import java.util.Scanner;
public class secondLargestInArr {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements: ");
int n=sc.nextInt();
int[] arr=new int[n];
System.out.println("Enter the elements: ");
for(int i=0; i<n; i++){
arr[i]=sc.nextInt();
}
int max= arr[0];
for(int i=0; i<n; i++){ //finding maximum value
if(arr[i]>max){max=arr[i];}
}
int secondLarge=arr[0];
for(int i=0; i<n; i++){ //finding second maximum
if(arr[i]>secondLarge && arr[i]!=max){secondLarge=arr[i];}
}
System.out.println("Second largest element is: "+secondLarge);
}
}