C Program to Search an Element in an Array (Binary search) - Source Code, Output & Execution Flow

C Program to Search an Element in an Array (Binary search)

This C program searches an element in a sorted array using binary search.

#include <stdio.h>
int main() {
    int a[] = {2, 4, 6, 8, 10, 12};
    int key = 10, low = 0, high = 5, mid, found = 0;
    while (low <= high) {
        mid = (low + high) / 2;
        if (a[mid] == key) { found = 1; break; }
        else if (a[mid] < key) low = mid + 1;
        else high = mid - 1;
    }
    if (found) printf("Element found at position %d
", mid + 1);
    else printf("Element not found
");
    return 0;
}
Element found at position 5

In this program, the input is read first when required, the core logic is applied step by step, and the final result is displayed using printf(). Follow the execution flow beside the code to understand how each statement contributes to the output.

Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗