Free C Programs  : Download Free C Language Programs/Logics

C Programming Logics/ Programs

Note: These C programs are submitted by users. You can also contribute to our site by sending your c programs at our E mail ID. (don't send copyrighted material).

/*Program for searching an element in an array using Binary search*/


#include"stdio.h"
#include"conio.h"
main()
{
 int a[20],n,i,beg,end,mid,item;
 clrscr();
 printf("Enter size of the array : ");
 scanf("%d",&n);
 printf("\nEnter elements in the array in sorted order: \n");
  for(i=0;i    scanf("%d",&a[i]);
 printf("\nEnter element to be searched : ");
 scanf("%d",&item);
  beg=0;end=n-1;
  mid=(beg+end)/2;

  while((beg<=end)&&(a[mid]!=item))
  {
    if(item       end=mid-1;
    else
      beg=mid+1;
     mid=(beg+end)/2;
  }

   if(item==a[mid])
    { printf("\nElement found at location %d",mid+1);
      getch();
      exit();
    }

    printf("\nElement %d is not in the array",item);
    getch();
}