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 cout<<"\nElement not found"; 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
there must be (flag==1) at the end…don't you think so?
if(flag) and if(flag==1), both have same meaning.
No only flag will return the default value 0
is flag taken as temperory variable????
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();
}
I think there’s something with your code :/
can variable i be used out of the for loop?
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
When you enter same element like1,2,5,1,6
Then it not show the loc of both 1