forked from ironhack-labs/lab-java-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayTasks.java
More file actions
55 lines (40 loc) · 1.29 KB
/
ArrayTasks.java
File metadata and controls
55 lines (40 loc) · 1.29 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
public class ArrayTasks {
// Difference between largest and smallest
public static int getDifference(int[] arr) {
int max = arr[0];
int min = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
return max - min;
}
// Smallest and second smallest
public static void findSmallestAndSecond(int[] arr) {
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];
}
}
System.out.println("Smallest: " + smallest);
System.out.println("Second Smallest: " + secondSmallest);
}
public static void main(String[] args) {
int[] numbers = {5, 2, 9, 1, 7};
// Task 1
int result = getDifference(numbers);
System.out.println("Difference: " + result);
// Task 2
findSmallestAndSecond(numbers);
}
}