by Dinesh Thakur Category: Array Pointer and Union

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

 

#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";

}

 

Input and Output:

 

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



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles