Linear search for a specific value
What you'll learn: How to use a loop to check every element in an array until you find the data you are looking for.
The "Flashlight" approach
Imagine you are looking for a specific book on a shelf, but the books aren't in alphabetical order. You don’t have a map, and you can’t see the whole shelf at once. What do you do? You start at the very first book on the left, check the title, and if it’s not the one, you move to the next. You keep doing this until you either find the book or run out of shelf.
In C, this is called a Linear Search. It is the most straightforward way to find a value in an array. You "shine your flashlight" on each index, one by one.
Implementing the search
To perform a linear search, we combine a for loop with an if statement. The loop handles the movement (moving from index 0 to n-1), and the if statement handles the comparison.
We often use a "flag" variable—usually an integer acting as a true/false toggle—to keep track of whether we actually found what we were looking for.
#include <stdio.h>
int main() {
int numbers[] = {12, 45, 7, 92, 31, 5};
int size = 6;
int target = 92; // The value we want to find
int foundIndex = -1; // -1 signifies we haven't found it yet
for (int i = 0; i < size; i++) {
// Check if the current element matches the target
if (numbers[i] == target) {
foundIndex = i; // Store the location
break; // Exit the loop early since we found it
}
}
if (foundIndex != -1) {
printf("Value %d found at index %d.\n", target, foundIndex);
} else {
printf("Value not found in the array.\n");
}
return 0;
}
Why use 'break'?
In the code above, the break keyword is a crucial efficiency trick. Once the computer finds the number 92 at index 3, there is no reason to waste energy checking indexes 4 and 5. The break command tells the program to jump out of the loop immediately. If the target was the very last item, or not there at all, the loop would simply finish on its own.
Key takeaway
Linear search visits every element in sequence using a loop to compare each item against a target value.