A directory of Objective Type Questions covering all the Computer Science subjects. Here you can access and discuss Multiple choice questions and answers for various compitative exams and interviews.

C program to read an Array and Search for an element


Problem Description


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.


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

#include <stdio.h>

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