Binary search in C: solved exercise
If you searched for binary search in C solved exercise, this page includes a clean iterative implementation and complexity notes.
Problem statement
Given a sorted array, return the target index or -1 if missing.
C solution
#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;
}Expected output
Index: 3Complexity
- Time: O(log n)
- Space: O(1)
Common mistakes
- Running it on unsorted arrays.
- Wrong midpoint calculation.
- Incorrect range updates (
l,r).
Practical use
Binary search appears in ordered catalogs, index systems, and high-performance query paths.
Recommended next exercise
- Merge sort in C: solved exercise with divide and conquer
- Bubble sort in C: solved exercise step by step
- Queue in C: solved exercise with circular array
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Is this exercise useful for C exams and technical interviews?
Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.
Where can I keep practicing with more solved C exercises?
In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.