#include <iostream>
usingnamespace std;
int main()
{
int n,num;
int arr[50];
cout<<"Enter the no. of elements of array"<<endl;
cin>>n;
cout<<"Enter the elements of array"<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int beg=0;
int endd=n-1;
int mid=(beg+endd)/2;
cout<<"Enter the element you want to search"<<endl;
cin>>num;
while(num!=arr[mid])
{
for(;;num!=arr[mid])
{
if(num<arr[mid])
{
endd=mid-1;
mid=(endd+beg)/2;
}
elseif(num>arr[mid])
{
beg=mid+1;
mid=(endd+beg)/2;
}
}
if(num==arr[mid])
{
cout<<"Search Successful"<<endl;
break;
}
}
}
Firstly you need to ensure that the elements are sorted.
Secondly, I would suggest that you read up on a binary search. Wikipedia has a good iterative version you could translate into C++. http://en.wikipedia.org/wiki/Binary_search_algorithm#Iterative