-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArray-1
More file actions
78 lines (65 loc) · 2.6 KB
/
Copy pathArray-1
File metadata and controls
78 lines (65 loc) · 2.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
Q1. Given an array of integers {2, 6, -5, -1, 0, 4, -9}, print only the positive values present in the array.
public class PositiveValues {
public static void main(String[] args) {
int[] arr = {2, 6, -5, -1, 0, 4, -9};
System.out.print("Positive values in the array: ");
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
System.out.print(arr[i] + " ");
}
}
}
}
Q2. Convert the list of Strings {“ab”, “bc”, “cd”, “de”, “ef”, “fg”, “gh”} into an array of strings and print all
strings stored on odd indices of the array.
import java.util.List;
import java.util.Arrays;
public class OddIndexStrings {
public static void main(String[] args) {
List<String> stringList = Arrays.asList("ab", "bc", "cd", "de", "ef", "fg", "gh");
String[] stringArray = stringList.toArray(new String[0]);
System.out.print("Strings stored on odd indices of the array: ");
for (int i = 1; i < stringArray.length; i += 2) {
System.out.print(stringArray[i] + " ");
}
}
}
Q3. Traverse over the elements of the array {1,2,3,4,5,6,7,8} using for each loop and print all even
elements.
public class EvenElements {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
System.out.print("Even elements in the array: ");
for (int num : arr) {
if (num % 2 == 0) {
System.out.print(num + " ");
}
}
}
}
Q4. Calculate the minimum element in the array {2, -3, 5, 8, 1, 0, -4} using standard library method
for calculating the minimum element.
import java.util.Arrays;
public class MinElement {
public static void main(String[] args) {
int[] arr = {2, -3, 5, 8, 1, 0, -4};
int min = Arrays.stream(arr).min().getAsInt();
System.out.println("Minimum element in the array: " + min);
}
}
Q5. Find the first peak element in the array {1, 1, 3, 4, 2, 3, 5, 7, 0}
Peak element is the one which is greater than its immediate left neighbor and its immediate right neighbor.
Leftmost and rightmost element cannot be a peak element.
public class FirstPeakElement {
public static void main(String[] args) {
int[] arr = {1, 1, 3, 4, 2, 3, 5, 7, 0};
int n = arr.length;
for (int i = 1; i < n - 1; i++) {
if (arr[i] > arr[i-1] && arr[i] > arr[i+1]) {
System.out.println("The first peak element is: " + arr[i]);
return;
}
}
System.out.println("No peak element found in the array.");
}
}