Monday, April 6, 2026

Write a program that uses non-recursive function to search for a Key value in a given sorted list of integers using binary search method. || C Lab Program

 WAP_F02: Write a C program that uses a non-recursive function to search for a Key value in a given sorted list of integers using binary search method.|| Sorting and Searching


WAP_F02: C Lab Program


//A non-recursive function to search for a Key value in a given sorted list of integers using binary search method.
#include <stdio.h>

int main() {
    int n, i, key, arr[20];
    int binarySearch(int [], int , int );
   
    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter %d sorted integers:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    printf("Enter key to search: ");
    scanf("%d", &key);

    int result = binarySearch(arr, n, key);

    if (result == -1)
        printf("Key %d not found in the list.\n", key);
    else
        printf("Key %d found at position %d (index %d).\n", key, result + 1, result);

    return 0;
}

// Iterative (non-recursive) binary search function
int binarySearch(int arr[], int n, int key) {
    int low = 0, high = n - 1;

    while (low <= high) {
        int mid = (low + high) / 2;

        if (arr[mid] == key)
            return mid;          // key found
        else if (arr[mid] < key)
            low = mid + 1;       // search in right half
        else
            high = mid - 1;      // search in left half
    }

    return -1; // key not found
}



OUTPUT


Enter number of elements: 10
Enter 10 sorted integers:
0 1 2 3 4 5 6 7 8 9
Enter key to search: 8
Key 8 found at position 9 (index 8)


For all 2026 published articles list: click here

...till the next post, bye-bye & take care

No comments:

Post a Comment