Q:

Write a C Program to perform Binary Search

0

Write a C Program to perform Binary Search. Here’s a Simple Program to perform Binary Search  in C Programming Language.

To perform binarysearch in C programming, you have to ask to the user to enter the array size then ask to enter the array elements. Now ask to enter an element to be search, to start searching that element using binary search technique.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Following C program first ask to the user to enter “how many element he want to store in the array”, then ask to enter the array element one by one.

After storing the element in the array, program ask to enter the element which he want to search in the array whether the number/element is present or not in the given array. The searching technique used here is binary search which is fast technique.


Below is the source code for C Program to perform Binary Search which is successfully compiled and run on Windows System to produce desired output as shown below :

 

SOURCE CODE : 

#include<stdio.h>
#include<conio.h>
int main()
{
        int a[25], i, n, K, flag = 0, low, high, mid;

        printf("Enter the number of elements :: ");
        scanf("%d", &n);
        printf("\nEnter the elements below ::\n");
        for(i = 0; i<n; i++)
        {
            printf("Enter %d element :: ",i+1);
                scanf("%d",&a[i]);
        }
        printf("\nEnter the key to be searched :: ");
        scanf("%d",&K);
        low = 0;
        high = n - 1;
        while(low <= high)
        {
                mid = (low+high)/2;
                if(a[mid] == K)
                {
                        flag = 1;
                        break;
                }
                else if(K<a[mid])
                        high = mid-1;
                else
                        low = mid + 1;
        }
        if(flag == 1)
        {
                printf("Key element is found");
        }
        else
        {
                printf("Key element not found");
        }
        return 0;
}

OUTPUT : :


Enter the number of elements :: 6

Enter the elements below ::
Enter 1 element :: 2
Enter 2 element :: 8
Enter 3 element :: 12
Enter 4 element :: 16
Enter 5 element :: 44
Enter 6 element :: 76

Enter the key to be searched :: 44

Key element is found

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a C program to perform Tower of Hanoi Algori... >>
<< Write a Menu Driven Program to implement stack ope...