In this tutorial you will learn about the Linear Search Algorithm and its application with practical example.
What Is Linear Search Algorithm?
Linear search algorithm is a simple search algorithm. Linear search algorithm is also known as sequential search algorithm. In this type of search algorithms, we simply search for an element or value in a given array by traversing the all array elements sequentially from the beginning of the array till the desired element or value is found. In Linear search, each array element is matched to find the desired search element. If a match found then location of the matched item is returned else it returns NULL.
Linear Search Program In 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 |
#include <stdio.h> int main() { int a[100], search, ctr, n; printf("Enter number of elements in array:\n"); scanf("%d", &n); printf("Enter %d integer numbers:\n", n); for (ctr = 0; ctr < n; ctr++) scanf("%d", &a[ctr]); printf("Enter a number to search:\n"); scanf("%d", &search); for (ctr = 0; ctr < n; ctr++) { if (a[ctr] == search) { printf("%d is found at location %d.\n", search, ctr+1); break; } } if (ctr == n) printf("%d is not found in the array.\n", search); return 0; } |
Output:-