Linear Search
Completed
Read n integers and a target. Print the index of the first occurrence of the target, or -1.
Input
n, the integers, then the target.
Output
An index.
Example
Input
5 4 8 15 16 23 15
Output
2
Editor
Java
Hints
Use an index loop so you know where the match is.
Solution explanation
Linear search checks each element in turn - simple, and works on unsorted data.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int target = sc.nextInt();
int index = -1;
for (int i = 0; i < n; i++) {
if (a[i] == target) {
index = i;
break;
}
}
System.out.println(index);
}
}