-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecondSmallestElement.java
More file actions
64 lines (52 loc) · 1.6 KB
/
SecondSmallestElement.java
File metadata and controls
64 lines (52 loc) · 1.6 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;
//24. Print the second smallest element in an array.
public class SecondSmallestElement
{
public static void printSecondSmallest(int[] arr)
{
if (arr.length < 2)
{
System.out.println("Array must contain at least two elements.");
return;
}
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] < smallest)
{
secondSmallest = smallest;
smallest = arr[i];
}
else if (arr[i] < secondSmallest && arr[i] != smallest)
{
secondSmallest = arr[i];
}
}
if (secondSmallest == Integer.MAX_VALUE)
{
System.out.println("No second smallest element exists.");
}
else
{
System.out.println("Second smallest element: " + secondSmallest);
}
}
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));
printSecondSmallest(arr);
sc.close();
}
}