Linear Search in C++ array : In linear search algorithm, we compare targeted element with each element of the array. If the element is found then its position is displayed.you have ask to the user to enter the array size and array elements to store the elements in the array.
Linear Search in C++ array
#include<iostream>
using namespace std;
int main()
{
int a[20],n,x,i,flag=0;
cout<<"How many elements?";
cin>>n;
cout<<"\nEnter elements of the array\n";
for(i=0;i<n;++i)
cin>>a[i];
cout<<"\nEnter element to search:";
cin>>x;
for(i=0;i<n;++i)
{
if(a[i]==x)
{
flag=1;
break;
}
}
if(flag)
cout<<"\nElement is found at position "<<i+1;
else
cout<<"\nElement not found";
return 0;
}
Output of Program
How many elements?5
Enter elements of the array
5
5
5
5
5
Enter element to search:1
Element not found