belongs to collection: C programs - Searching and Sorting
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
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
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
C program to read an Array and Search for an element - Source code
Program Output
need an explanation for this answer? contact us directly to get an explanation for this answer