Linear Search in C: A Beginner-Friendly Guide


Searching is one of the most essential operations in programming, especially when dealing with data. Among various search algorithms, Linear Search is the simplest and most straightforward. This blog will help you understand what linear search is, how it works in C, and where it’s most useful.


What is Linear Search?

Linear search (also known as sequential search) is a method for finding a specific value in a list. It checks each element of the list, one by one, until the target value is found or the list ends.

Key Characteristics:

  • Simple and easy to implement
  • Works on both sorted and unsorted arrays
  • Time complexity: O(n)
  • Best suited for small datasets

How Linear Search Works in C

Let’s look at a simple C program that performs a linear search.

cCopyEdit#include <stdio.h>

int linearSearch(int arr[], int size, int key) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == key) {
            return i; // Return index if key is found
        }
    }
    return -1; // Return -1 if key is not found
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int key = 30;
    int size = sizeof(arr) / sizeof(arr[0]);

    int result = linearSearch(arr, size, key);

    if (result != -1) {
        printf("Element found at index: %d\n", result);
    } else {
        printf("Element not found in the array.\n");
    }

    return 0;
}

Step-by-Step Explanation

  1. Function Definition: The linearSearch function takes the array, its size, and the key to be searched.
  2. Loop Through Array: A for loop iterates through each element.
  3. Compare Elements: Each element is compared with the key.
  4. Return Result: If a match is found, the index is returned. Otherwise, -1 indicates the key wasn’t found.

Advantages of Linear Search

  • Easy to understand and implement
  • No need for sorting the data
  • Can be used with arrays, linked lists, or any sequential collection

Disadvantages

  • Inefficient for large datasets
  • Takes more time compared to binary search in sorted arrays

When to Use Linear Search?

Use linear search when:

  • The dataset is small
  • The data is unsorted
  • Simplicity is more important than speed

Final Thoughts

Linear search is a great starting point for beginners learning about search algorithms in C. While it may not be the most efficient for large datasets, it’s perfect for understanding basic logic and control flow.

👉 Apply now and take your first step towards a successful career in tech!
Explore our placement guarantee programs