This article describes how to perform Linear search in C/C++? Let us discuss about linear search.
What is Linear Search?
Linear search or sequential search is a method for finding a particular value in a list by checking every one of its elements until the desired one is found. Every element is searched one at a time and in sequence. It is the simplest search algorithm. t is a special case of brute-force search.
This searching algorithm is not efficient for large number of element. For large element we can use binary search or hashing.
Searching is one of the important mechanism in computer programming. It plays a good role to make a program slow or fast based on choice appropriate searching mechanism.
#include
#include
int main(){
clrscr();
int n,i,loc;
float data[100],item;
cout<<” ” This Program will show linear search. “”<<endl<<endl;
xx:
cout<<“How many number’s ?. Give a integer number.”<<endl;
cin>>n;
if(n<0) {
cout<<“Negatve number is not allow, Please give a integer number.”<<endl;
goto xx;
}
cout<<“What are the elemnents ?. Give some data.”<<endl;
for(i=1;i<=n;i++)
cin>>data[i];
cout<<“What is the data that you want to search ?. Givea a number.”<<endl;
cin>>item;
for(i=1;i<=n;i++)
if(data[i]==item)
loc=i;
else loc=0;
cout<<endl;
cout<<“You have given the following data.”<<endl;
for(i=1;i<=n;i++)
cout<<data[i]<<” “;
cout<<endl;
cout<<“Yoy have given “<<item<<” to search from the above data.”<<endl;
cout<<“Searching result :”<<endl;
if (loc==0)
cout<<item<<” is not present here. “;
else
cout<<item<<” is present here and it’s psition is : “<<loc;
getch();
}