Q:

C program to read an Array and Search for an element

belongs to collection: C programs - Searching and Sorting

0

This C Program reads an array and searches for an element. Binary search is used for the searching purpose so the entered array must be in sorted order.

All Answers

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

C program to read an Array and Search for an element - Source code

void main()
{
    int arr[20];
    int i, low, mid, high, key, size;
 
    printf("Enter the size of an array\n");
    scanf("%d", &size);
    printf("Enter the array elements\n");
    for (i = 0; i < size; i++)
    {
        scanf("%d", &arr[i]);
    }
    printf("Enter the key\n");
    scanf("%d", &key);
 
    /*  search operation */
    low = 0;
    high = (size - 1);
    while (low <= high)
    {
        mid = (low + high) / 2;
        if (key == arr[mid])
        {
            printf("SUCCESSFUL SEARCH\n");
            return;
        }
        if (key < arr[mid])
            high = mid - 1;
        else
            low = mid + 1;
    }
    printf("UNSUCCESSFUL SEARCH\n");
}

Program Output

Enter the size of an array
6
Enter the array elements
100
200
300
400
500
600
Enter the key
500
SUCCESSFUL SEARCH

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
C program to implement Linear Search... >>