C Program to search an element using linear search or binary search (menu driven program)

How to write a C Program to search an element using linear search or binary search (menu driven program) in C Programming Language ?


This C Program to search an element using linear search or binary search (menu driven program).

Solution:


  1. #include<stdio.h>
  2. void main()
  3. {
  4. int a[25],beg,item,last,n,num,i,ch,mid,f=0;
  5. printf("menu\n");
  6. printf("\n 1.linear search");
  7. printf("\n 2.binary search");
  8. printf("\n enter the choice");
  9. scanf("%d",&ch);
  10. if(ch==1)
  11. {
  12. printf("\n enter the number of elements in the array");
  13. scanf("%d",&n);
  14. printf("\n enter the sorted array");
  15. for(i=0;i<n;i++)
  16. scanf("%d",&a[i]);
  17. printf("\n enter the item to be searched");
  18. scanf("%d",&item);
  19. for(i=0;i<n;i++)
  20. {
  21. if(a[i]==item)
  22. {
  23. printf("\n item found at position%d",i+1);
  24. break;
  25. }
  26. }
  27. if(i==n)
  28. printf("\n item not found");
  29. }
  30. if(ch==2)
  31. {
  32. printf("\nenter the number of elements in the array");
  33. scanf("%d",&n);
  34. printf("enter the sorted array");
  35. for(i=0;i<n;i++)
  36. scanf("%d",&a[i]);
  37. printf("item to be searched");
  38. scanf("%d",&item);
  39. last=n-1;
  40. mid=(beg+last)/2;
  41. while(beg<=last)
  42. {
  43. if(item==a[mid])
  44. {
  45. printf("\n item found at position %d",mid+1);
  46. break;
  47. }
  48. else if(a[mid]>item)
  49. last=mid-1;
  50. else beg=mid+1;
  51. mid=(beg+last)/2;
  52. }
  53. }
  54. }


Learn More :