# Linear Search in C++

Here you will get program for linear search in C++.

In linear search algorithm, we compare targeted element with each element of the array. If the element is found then its position is displayed.

The worst case time complexity for linear search is O(n).

## Program for Linear Search in C++

```#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

return 0;
}```

Output

How many elements?4

Enter elements of the array
5 9 12 4

Enter element to search:9

Element is found at position 2

### 9 thoughts on “Linear Search in C++”

1. as a bigner i have a simple program for linear search.
#include
#include
void main()
{
int list[5]={10,20,30,40,50};
for (int i=0; i<5; i++)
cout<<list[i]<<"\t";
int key,loc;
loc=-1;
cout<> key;
for(int i=0; i<5; i++)
if (list[i]==key)
{
loc=i;
i=5;
}
if (loc==-1)
cout<<"\n SEARCH UN-SUCCESSFULL";
else
cout<<"\n SEARCH SUCCESSFULL";
getch();
}

2. well i am following you blog for quite sometime, all i want to say is a big THANK YOU! as a programmer, i respect how you are help the community
best wishes