-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq3.java
More file actions
42 lines (29 loc) · 1.03 KB
/
q3.java
File metadata and controls
42 lines (29 loc) · 1.03 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
import java.util.Scanner;
public class q3 {
public static int linearSearch(int[] arr, int target) {
// Enhanced for loop implementation
int index = 0;
for (int num : arr) {
if (num == target) {
return index; // Return index if found
}
index++;
}
return -1; // Return -1 if not found
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] numbers = {4, 2, 7, 1, 9, 5, 8};
System.out.println("Enter Number you want");
int get_num = scan.nextInt();
int target = get_num;
// int target = 7;
int result = linearSearch(numbers, target);
if (result != -1) {
System.out.println("Element " + target + " found at index: " + result);
} else {
System.out.println("Element " + target + " not found in the array");
}
scan.close();
}
}