-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecondLargest.java
More file actions
53 lines (36 loc) · 1.23 KB
/
SecondLargest.java
File metadata and controls
53 lines (36 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package DSA;
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args){
//SECOND LARGEST VAR IS STORED AS -1 AS WE ARE ASSUMING ARRAY CONTAINS ALL POSITIVE ELEMENTS
Scanner sc = new Scanner(System.in);
int size=0;
System.out.print("Enter the size of array : ");
size = sc.nextInt();
sc.nextLine();
int[] arr = new int[size];
System.out.println("\nEnter the array elements : ");
for(int i=0;i<arr.length;i++){
System.out.printf("Element %d : ",i);
arr[i]=sc.nextInt();
sc.nextLine();
}
int largest=arr[0];
int secLargest=-1;
int i=0;
for(i=1;i<arr.length;i++){
if(arr[i]>largest){
largest=arr[i];
secLargest=arr[i-1];
}
else if(arr[i]<largest && arr[i]>secLargest){
secLargest=arr[i];
}
}
System.out.print("\nArray is : ");
for(i=0;i<arr.length;i++){
System.out.print(arr[i] + " ");
}
System.out.print("\nSecond Largest : " + secLargest);
}
}