Binary search in C: solved exercise on sorted arrays

  2 minutes

If you searched for binary search in C solved exercise, this page includes a clean iterative implementation and complexity notes.

Given a sorted array, return the target index or -1 if missing.

#include <stdio.h>

int binary_search(int a[], int n, int target) {
    int l = 0, r = n - 1;

    while (l <= r) {
        int m = l + (r - l) / 2;

        if (a[m] == target) return m;
        if (a[m] < target) l = m + 1;
        else r = m - 1;
    }

    return -1;
}

int main(void) {
    int a[] = {2, 5, 9, 12, 18, 25};
    int idx = binary_search(a, 6, 12);

    printf("Index: %d\n", idx);
    return 0;
}
Index: 3
  • Time: O(log n)
  • Space: O(1)
  • Running it on unsorted arrays.
  • Wrong midpoint calculation.
  • Incorrect range updates (l, r).

Binary search appears in ordered catalogs, index systems, and high-performance query paths.

If you want a complete path with progressive difficulty:

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.