hello guys . the code is doin well
enter sorted integers and num to be searched
the problem is in the last if condition

#include<iostream.h>
#include<conio.h>
#define siz 10
void main()
{
 int arra[siz]={0};
 int mid,beg=1,end=siz,loca=0,num;
 clrscr();
 cout<<"Please Enter The Elements Of Array\n";
  for(loca=0;loca<siz;loca++)
     {
      cin>>arra[loca];
     }
 cout<<"Please enter the required number";
 cin>>num;
 mid=(loca)/2;
     while(beg<end&&arra[mid]!=num)
  {
   if(num<arra[mid])
      end=mid-1;
   else
      beg=mid+1;
  mid=(beg+end)/2;
  }
 if (arra[mid]!=num)
    cout<<"\nnot found";
 else if (arra[mid]==num)
    cout<<"location is\t"<<mid;
 getch();
}

Maybe you should sort the numbers first before searching them?

[edit] Your program seems to work fine as long as the numbers are entered in the correct order:

Please Enter The Elements Of Array
 2
5
8
9
12
13
14
17
18
20
Please enter the required number18
location is    8

The only thing I'd suggest changing is perhaps adding +1 to the answer so that the user doesn't get confused with arrays starting at 0.

last if condition is not working . if the no is not fount then it should print not found but it is doing something else

1. I didn't know that binary searches work on un-sorted list.
2. For the last if thing not working I think it's a flushing problem try this:

if (arra[mid]!=num)
    //NOTE THE EXTRA flush AT END.
    //FYI endl = flush + "\n" (so that can also be used)
    cout<<"\nnot found" << flush ;
 else if (arra[mid]==num)
    cout<<"location is\t"<<mid;
 getch();
}

thanks for the help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.