Linear Search
Completed
Read n integers and a target. Print the first index 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
C
Hints
Read all numbers and the target before searching.
Solution explanation
Linear search works on unsorted data and stops at the first match.
Show solution
#include <stdio.h>
int main() {
int n, a[100], target, index = -1;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
scanf("%d", &target);
for (int i = 0; i < n; i++) {
if (a[i] == target) {
index = i;
break;
}
}
printf("%d\n", index);
return 0;
}