Linear search in C: solved exercise on unsorted arrays
Linear search in C: solved exercise step by step
If you searched for a solved linear search exercise in C, here is the full implementation with index return and the element-not-found case.
Linear search (also called sequential search) scans the array element by element until it finds the target value or reaches the end. It is the simplest search algorithm and the only one that works on unsorted arrays.
Problem statement
- Implement
linear_searchthat receives an array, its size, and a target value, and returns the index of the first occurrence or-1if not found. - Test it with a successful search and a value that is not in the array.
- Also implement
linear_search_allthat returns every index where the value appears (for repeated elements).
C solution
Expected output
Complexity
| Case | Comparisons | Complexity |
|---|---|---|
| Best case (first element) | 1 | O(1) |
| Average case | n/2 | O(n) |
| Worst case (last or not found) | n | O(n) |
Linear search vs binary search
| Feature | Linear | Binary |
|---|---|---|
| Requires sorted array | No | Yes |
| Complexity | O(n) | O(log n) |
| Implementation | Very simple | Moderate |
| Best for | Small or unsorted arrays | Large already-sorted arrays |
Common mistakes
- Returning
0instead of-1when not found:0is the valid index of the first element. - Using
>=instead of<in the loop condition and going out of bounds. - Continuing the loop after finding the element when only the first occurrence is needed.
Practical use
Linear search is used when:
- the array is unsorted and sorting it is not worth the cost,
- the array is small (< ~100 elements) and performance difference is irrelevant,
- you need to find all occurrences of a value, not just the first.
Recommended next exercise
- Binary search in C: solved exercise
- Bubble sort in C: solved exercise
- Recursion in C: solved exercise
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
When is linear search better than binary search?
When the array is unsorted. Sorting it first would cost O(n log n), which only pays off if you need to run many searches afterward.
Can linear search work on string arrays?
Yes, but you must use strcmp instead of ==: if (strcmp(a[i], target) == 0).
Is there a standard linear search function in C?
Not directly. bsearch from <stdlib.h> performs binary search (requires a sorted array). For linear search you need to implement it manually.