-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecondLargestElement.java
More file actions
65 lines (52 loc) · 1.59 KB
/
SecondLargestElement.java
File metadata and controls
65 lines (52 loc) · 1.59 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
54
55
56
57
58
59
60
61
62
package array_Programming.medium.day_11;
import java.util.Arrays;
import java.util.Scanner;
//23. Print the second largest element in an array.
public class SecondLargestElement
{
public static void printSecondLargest(int[] arr)
{
if (arr.length < 2)
{
System.out.println("Array must contain at least two elements.");
return;
}
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] > largest)
{
secondLargest = largest;
largest = arr[i];
}
else if (arr[i] > secondLargest && arr[i] != largest)
{
secondLargest = arr[i];
}
}
if (secondLargest == Integer.MIN_VALUE)
{
System.out.println("No second largest element exists.");
}
else
{
System.out.println("Second largest element: " + secondLargest);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter " + size + " elements:");
for (int i = 0; i < arr.length; i++)
{
arr[i] = sc.nextInt();
}
System.out.println("Array: " + Arrays.toString(arr));
printSecondLargest(arr);
sc.close();
}
}