-
Notifications
You must be signed in to change notification settings - Fork 5
/
linear_search.c
52 lines (41 loc) · 906 Bytes
/
linear_search.c
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
#include <stdio.h>
#include <stdlib.h>
/**
* Linear search algorithm.
*
* @param int a Search array
* @param int find Data to search
* @param int n Number of data in search array
*
* @return int Index of found data or -1
*/
int linear_search(int *a, int find, int n)
{
for (int i = 0; i < n; i++) {
if (find == *(a+i)) {
return i;
}
}
return -1;
}
int main()
{
int n, find;
printf("How many items? ");
scanf("%d", &n);
int *input = (int *) malloc(n * sizeof(int));
printf("Enter numbers: ");
for (int i = 0; i < n; i++) {
scanf("%d", input + i);
}
printf("Find: ");
scanf("%d", &find);
int position = linear_search(input, find, n);
if (position != -1) {
printf("Data found at position %d", position);
} else {
printf("Data not found");
}
free(input);
return 0;
}