Course contentsShow
← C
Lesson 1061 of 1,21914. Data Structures in CFree lesson

Linear Search on arrays

Linear Search on arrays

What you'll learn: How to find a specific value in an array by checking each element one by one from start to finish.

The Grocery Aisle Analogy

Imagine you are standing in a long grocery aisle looking for a specific brand of cereal. You don't know exactly where it is, so you start at the very beginning of the shelf. You look at the first box. If it’s not what you want, you move to the second box. You keep shuffling down the aisle, one box at a time, until you either find your cereal or reach the end of the shelf and realize it’s not there.

In programming, this is called Linear Search. It is the most straightforward way to search for data because it doesn't require the array to be sorted or organized in any special way.

How it works in C

To perform a linear search, we use a for loop to iterate through the array. Inside the loop, we use an if statement to compare the current element with our "target" value.

If the values match, we have found our item and can stop searching. If we finish the entire loop without finding a match, we conclude the item doesn't exist in the array.

#include <stdio.h>

int main() {
    int numbers[] = {12, 45, 7, 23, 9, 56};
    int size = 6;
    int target = 23;
    int foundIndex = -1; // -1 signifies the item wasn't found

    for (int i = 0; i < size; i++) {
        // Compare current element to the target
        if (numbers[i] == target) {
            foundIndex = i; // Save the position
            break;          // Exit the loop early
        }
    }

    if (foundIndex != -1) {
        printf("Found %d at index %d.\n", target, foundIndex);
    } else {
        printf("Value not found.\n");
    }

    return 0;
}

Why use Linear Search?

Linear search is excellent for small datasets or unsorted lists where you can't use more advanced methods. While it might be slow for an array of a billion items (because you might have to check every single one), it is simple to write, easy to debug, and works on any collection of data.

Key takeaway

Linear search checks every element in an array sequentially until it finds the target or hits the end.