ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-202 min read

Implement Linear Search in C for unsorted arrays. Step-by-step element search trace, best/worst case comparisons, and sample code included.

How Linear Search Works

Linear Search (also called sequential search) is the simplest searching algorithm. It starts from the first element of an array and compares every element with the target value sequentially until a match is found or the end of the array is reached.


C Code Implementation

c (ISO Standard)
#include <stdio.h>

int linearSearch(const int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i; /* Target found at index i */
        }
    }
    return -1; /* Target not found */
}

int main() {
    int dataset[] = {10, 50, 30, 70, 80, 20, 90, 40};
    int size = sizeof(dataset) / sizeof(dataset[0]);

    int target1 = 70;
    int target2 = 99;

    int idx1 = linearSearch(dataset, size, target1);
    int idx2 = linearSearch(dataset, size, target2);

    printf("Search for %d: %s (Index %d)\n", target1, (idx1 != -1 ? "FOUND" : "NOT FOUND"), idx1);
    printf("Search for %d: %s\n", target2, (idx2 != -1 ? "FOUND" : "NOT FOUND"));

    return 0;
}

Sample Output

text (ISO Standard)
Search for 70: FOUND (Index 3)
Search for 99: NOT FOUND

Complexity Analysis

  • Best Case Time: O(1) (When target is the first element).
  • Worst & Average Case Time: O(n) (When target is at the end or absent).
  • Space Complexity: O(1) constant memory.
  • Array Requirement: Works on both sorted and unsorted collections.

Related C Examples & Tutorials