TheAlgorithms-C/searching/Linear_Search.c

33 lines
715 B
C
Raw Normal View History

2017-10-14 10:16:21 +08:00
#include <stdio.h>
2017-10-14 10:08:58 +08:00
2020-04-08 21:41:12 +08:00
int linearsearch(int *arr, int size, int val)
{
2017-10-14 10:08:58 +08:00
int i;
2020-04-08 21:41:12 +08:00
for (i = 0; i < size; i++)
{
2017-10-14 10:08:58 +08:00
if (arr[i] == val)
return 1;
}
return 0;
}
2020-04-08 21:41:12 +08:00
int main()
{
int n, i, v;
2017-10-14 10:08:58 +08:00
printf("Enter the size of the array:\n");
2020-04-08 21:41:12 +08:00
scanf("%d", &n); //Taking input for the size of Array
2017-10-14 10:08:58 +08:00
2019-10-02 11:41:55 +08:00
int a[n];
2019-10-03 11:34:29 +08:00
printf("Enter the contents for an array of size %d:\n", n);
2020-04-08 21:41:12 +08:00
for (i = 0; i < n; i++)
scanf("%d", &a[i]); // accepts the values of array elements until the loop terminates//
2017-10-14 10:08:58 +08:00
printf("Enter the value to be searched:\n");
2019-10-02 11:41:55 +08:00
scanf("%d", &v); //Taking input the value to be searched
2020-04-08 21:41:12 +08:00
if (linearsearch(a, n, v))
2017-10-14 10:16:21 +08:00
printf("Value %d is in the array.\n", v);
2017-10-14 10:08:58 +08:00
else
2017-10-14 10:16:21 +08:00
printf("Value %d is not in the array.\n", v);
2020-04-08 21:41:12 +08:00
return 0;
2017-10-14 10:08:58 +08:00
}