W.A.P. C++

WAP | CPP | Programs in C++ | C++ Solutions

Write a program to search an element in an array (Binary searching)


Size of array is taken from user.. Elements are entered by user in order (ascending or descending).. user is asked for the element to be searched... Search is performed..
Select To use this code as it is.. select and copy paste this code into code.cpp file :)
  1. #include<conio.h>
  2. #include<iostream.h>
  3. void main()
  4. {
  5. clrscr();
  6. int a[100],i,loc,mid,beg,end,n,flag=0,item;
  7. cout<<"How many element: ";
  8. cin>>n;
  9. cout<<"Enter (IN ORDER) the elements of array: "<<endl;
  10. //Coding by: Snehil Khanor
  11. //http://WapCPP.blogspot.com
  12. for(i=0;i<n;i++)
  13. cin>>a[i];
  14. cout<<"Enter the element to be searched: ";
  15. cin>>item;
  16. loc=0;
  17. beg=0;
  18. end=n-1;
  19. while((beg<=end)&&(item!=a[mid]))
  20. {
  21. mid=(beg+end)/2;
  22. if(item==a[mid])
  23. {
  24. cout<<"Search successful :)";
  25. loc=mid;
  26. cout<<"Position of the Item: "<<loc+1;
  27. flag=flag+1;
  28. }
  29. else if(item<a[mid])
  30. end=mid-1;
  31. else
  32. beg=mid+1;
  33. }
  34. if(flag==0)
  35. {
  36. cout<<"Search NOT sucessfull :( ";
  37. }
  38. getch();
  39. }

1 comments:

Anonymous November 18, 2009 at 3:07 PM  

It's wrong.. The while loop is while(beg<=end)..

Search

About WAP C++

Here you'll find a wide range of programs' solution ranging from beginer level to advanced level.
All programs here are made, compiled and tested by me..and are running absolutely fine.. still if you find any bug in any program do let me know :)

Followers

Subscribe via email

Enter your email address:

Delivered by FeedBurner

my Binary Log

Recent Posts

Blog Archive



eXTReMe Tracker