Home / Programs / Write a program that uses the binary search algorithm to find out the position where the given key element exist in a user chosen array and print it as output.
🚀 Programming Example

Write a program that uses the binary search algorithm to find out the position where the given key element exist in a user chosen array and print it as output.

👁 914 Views
💻 Practical Program
📘 Step Learning
Write a program that uses the binary search algorithm to find out the position where the given key element exist in a user chosen array and print it as output.

💻 Program Code

#include <stdio.h>
#include <stdlib.h>
int main()
{
  int a[30],n,i,t,low,mid,high,found=0;
  printf("\n Enter the NO. of elements in the array: ");
  scanf("%d",&n);
   if(n>30)
    {
      printf("\n Too many Numbers");
      exit(0);
     }
  printf("\n Enter the elements of the array:\n");
   for(i=0 ; i< n; i++)
    scanf("%d", &a[i]);
  printf("\n Enter the element to search :");
  scanf("%d",&t);
  low = 0;
  high = n - 1;
   while(high >= low)
   {
     mid = (low + high) / 2;
     if(a[mid] == t)
      {
        found = 1;
        break;
       }
     else if (t < a[mid])
      high = mid - 1;
     else
      low = mid + 1;
    }

  if(found==0)
   printf("\n NOT FOUND");
  else
   printf("\n FOUND AT %d",mid);

  return 0;

}


                        

🖥 Program Output


 Enter the NO. of elements in the array: 5

 Enter the elements of the array:
5
4
9
2
3

 Enter the element to search :9

 FOUND AT 2 
                            

📘 Explanation

None
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.