The linear search procedure gives the method of finding whether an element is present in a set of elements (array) or not. The given element is compared with each element in the set one by one. The process is repeated until a perfect match is found. The array comprises of unsorted elements.
Example
Write a C++ Program for Linear Search
Input and Output:
#include <iostream.h> void main() { int m,i=0,p=0; int s[5]; cout<<"Enter Five elements in unsorted order"; for(i=0;i<5;i++) cin>>s[i]; cout<<"Enter the element to be searched "; cin>>m; i=0; while(i<5) { if (m==s[i]) { cout<<endl; cout<<"Number is present in the array at "<<" position "<<i+1; p=1; break; } i++; } if (p!=1) cout<<"number is not present in the list"; }
Enter Five elements in unsorted order 6 2 9 5 12
Enter the element to be searched 9
Number is present in the array at position 3