-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinear_search.c
73 lines (58 loc) · 1.63 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* LINEAR SEARCH */
/*##################################################################################################3*/
#include<stdio.h>
int main()
{
int n, i;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n], value;
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Enter the value to search for: ");
scanf("%d", &value);
for (i=0; i<n; i++)
{
if (arr[i] == value)
{
printf("Element found at index - %d.\n", i);
break;
}
}
if (i == n)
printf("Element not found!\n");
return 0;
}
/*##################################################################################################3*/
/* Another Way, */
#include <stdio.h>
int linearSearch(int arr[], int n, int key)
{
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
return i;
}
return -1;
}
int main()
{
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n], i;
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
int key;
printf("Enter the value to search for: ");
scanf("%d", &key);
int result = linearSearch(arr, n, key);
if (result != -1)
printf("Element %d found at index %d\n", key, result);
else
printf("Element %d not found in the array.\n", key);
return 0;
}
/*##################################################################################################3*/