This C++ program implements linear search. In this method all the elements in the list will be checked in a sequential order, to check for a match with the element to be searched. If a match is found the iteration will be stopped and the element will be returned with its position. The program reads the size of the array in the variable n, then the elements are read into the array a[] by using a for loop. Next the element to be searched is read into the variable elem. Then the program uses a for loop to check all the elements in the array with the value of elem to find a match.
Program
#include<iostream.h>
#include<conio.h>
void main()
{
int a[50],f=0,elem,*p,i,n;
cout<<"Enter the size of the array: ";
cin>>n;
p=a;
cout<<"Enter the elements: ";
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Enter the element to be searched: ";
cin>>elem;
for(i=0;i<n;i++)
{
if(*p==elem)
{
cout<<"\nItem Found at position "<<i+1;
f=1;
break;
}
p++;
}
if(f==0)
cout<<"\nItem not found";
getch();
}
Linear search in C++ |
No comments:
Post a Comment