C Programming Tutorial

Advertisements

Write a program to search a number in an array using binary search in C



       //Note : For binary search array must be in order, ascending or descending.
                   For the following program, enter numbers in ascending order.
              
       #include<stdio.h>
       #include<conio.h>
       void main()
       {
              int arr[10],i,num,mid,lb=0,ub=9; 
              char found='n';
              clrscr();

              for(i=0;i<10;i++)
              {
                 printf("Enter any number : "); 
                 scanf("%d",&arr[i]); 
              }

              printf("\nEnter any number for search : "); 
              scanf("%d",&num); 
              
              while(lb<=ub)
              {
                     mid = (lb + ub)/2;
                     
                     if(num == arr[mid])
                     {
                           found='y';
                           break;
                     }
                     else if(num>arr[mid])
                           lb = mid + 1;
                      else
                           ub = mid - 1;
              }
              
              if(found=='y')
                     printf("\nMatch found at %d",mid);                
              else
                     printf("\nNo match found.");              

              getch();
       }

   Output : 

              Enter any number : 12
              Enter any number : 23
              Enter any number : 34
              Enter any number : 45
              Enter any number : 56
              Enter any number : 67
              Enter any number : 78
              Enter any number : 89
              Enter any number : 91
              Enter any number : 95
              
              Enter any number for search : 67
              
              Match found at 5




Advertisement