LINEAR
SEARCH
Write a C++ program to accept a single dimensional
array and search for an element by Linear search.
#include<iostream.h>
#include<conio.h>
int lsearch(int[],int,int);
void main()
{
clrscr();
int a[50],item,n,index;
cout<<"Enter array size ";
cin>>n;
cout<<"\nEnter array elements
:";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"\nEnter an element to be
searched for";
cin>>item;
index = lsearch(a,n,item);
if(index==-1)
cout<<"Given
element not found";
else
cout<<"\nElement
found at index :"<<index<< ", position :"<<index+1<<endl;
getch();
}
int lsearch(int a[],int size,
int item)
{
for(int
i=0;i<size;i++)
{
if(a[i]==item)
return i;
}
return
-1;
}
No comments:
Post a Comment