Are you new to programming and struggling to understand how searching works in C? Let’s simplify it! In this guide, we’ll break down the linear search program in C step-by-step, with real-life examples and code even a 10-year-old can grasp. By the end, you’ll know how to find elements in an array like a pro!
Imagine you’ve lost your favorite toy in a messy room. How do you find it? You check each item one by one until you spot it. That’s exactly what linear search does! It’s a basic algorithm that checks every element in a list (or array) sequentially until it finds the target value.
Why Learn Linear Search?
Let’s say we have an array: [5, 3, 8, 2, 9]
and want to find the number 8. Here’s how linear search works:
Time Complexity: O(n) – Worst case, it checks all elements.
#include <stdio.h>
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return position if found
}
}
return -1; // Return -1 if not found
}
int main() {
int arr[] = {5, 3, 8, 2, 9};
int target = 8;
int size = sizeof(arr) / sizeof(arr[0]);
int result = linearSearch(arr, size, target);
if (result != -1) {
printf("Element found at position: %d", result);
} else {
printf("Element not found!");
}
return 0;
}
linearSearch()
takes three arguments: the array, its size, and the target value.for
loop checks each element against the target.-1
.Think of linear search like scrolling through your WhatsApp chats to find a specific message. You start from the top and scroll down until you spot it. It’s not the fastest method for long chats, but it works!
Pro Tip: For large datasets, use binary search (but only if the array is sorted!).
0
to size-1
.-1
to handle “not found” cases.Q1. What if there are duplicate elements?
A1. Linear search returns the first occurrence of the target. Modify the code to collect all positions if needed.
Q2. Is linear search inefficient?
A2. For small data, it’s fine. For large data, use better algorithms like binary search.
Modify the program to count how many times a number appears in the array.
(Hint: Use a counter variable inside the loop!)
Linear search is the ABC of searching algorithms. It’s easy, intuitive, and a great starting point for new programmers. Try tweaking the code above, experiment with different arrays, and soon you’ll master searching in C!
Found this helpful? Share it with a friend struggling with C programming!
Buy Best Coding Laptop with discount rate – https://amzn.to/3X2EgHb