Here you will find program for linear search in C.
Linear search is the simplest searching algorithm which is sometimes known as sequential search. In this algorithm each element of array is compared with the targeted element sequentially.
Linear Search in C
#include<stdio.h> int main() { int a[20],i,x,n; printf("How many elements?"); scanf("%d",&n); printf("Enter array elements:\n"); for(i=0;i<n;++i) scanf("%d",&a[i]); printf("\nEnter element to search:"); scanf("%d",&x); for(i=0;i<n;++i) if(a[i]==x) break; if(i<n) printf("Element found at index %d",i); else printf("Element not found"); return 0; }
Output
How many elements?4
Enter array elements:
6 8 9 1
Enter element to search:9
Element found at index 2
can’t understand why if(i<n)
If desired element is not found then all the elements in the array would be traversed so in that case value of i would not be less than n.
I want algorithm for it
ITS IS COMPLIED SUCCESSFULLY
BUT NOT RUNNED