C Program to Search an Element in an Array Using Binary Search

 #include<stdio.h>

void main()

{

    int a[50],n,i,l=0,h,m,ele;


    do

    {

        printf("\nEnter no. of elements in between 1 and 50: ");

        scanf("%d",&n);

    }while(n<1 || n>50);


    printf("\nEnter the elements (in sorted order): ");

    for(i=0;i<n;i++)

        scanf("%d",&a[i]);


    h=n-1;


    printf("\nEnter an element for search: ");

    scanf("%d",&ele);


    while(l<=h)

    {

        m=(l+h)/2;


        if(ele==a[m])

        {

            printf("\nFound at a[%d]",m);

            break;

        }


        if(ele>a[m])

            l=m+1;

        else

            h=m-1;

    }


    if(l>h)

        printf("\nNumber is not found");

}

Comments

Popular posts from this blog

Single Program Using All Automatic String Functions

C program for subtraction of two matrices (2D Arrays)

C program for Multiplication of Two matrices