Computer Science Of Engineering

Simple and practical computer science tutorials, programming guides, and engineering concepts for students and beginners.

Breaking

Friday, April 18, 2025

C Program to implement the Searching Technique - Binary Search

  C Program to implement the Searching Technique - Binary Search 

Binary Search (only works on sorted arrays)

Program:

#include <stdio.h>


int main() {

    int arr[100], n, i, key, low, high, mid;


    printf("Enter number of elements: ");

    scanf("%d", &n);


    printf("Enter %d elements in sorted order:\n", n);

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

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

    }


    printf("Enter the element to search: ");

    scanf("%d", &key);


    low = 0;

    high = n - 1;


    while(low <= high) {

        mid = (low + high) / 2;


        if(arr[mid] == key) {

            printf("Element found at position %d (index %d)\n", mid + 1, mid);

            return 0;

        } else if(arr[mid] < key) {

            low = mid + 1;

        } else {

            high = mid - 1;

        }

    }


    printf("Element not found in the array.\n");

    return 0;

}

Output(s):



No comments:

Post a Comment