hello everyone
In today’s blog, we’re on a fun mission to find a missing friend (or value) using the Linear Search technique in C. If you remember how we handled friends in the “Array Operations” blog, this time too, our group of friends will help us understand how searching works!
What is Linear Search?
Imagine your friends standing in a line each one holding a number card. You need to find the friend who’s holding a specific number (say 30). How do you do it? Simple you start from the first friend and ask one by one:
“Hey, do you have 30?” If someone says yes mission complete! If you reach the end and no one has 30 well, your friend didn’t show up. That’s Linear Search checking every element in the array, one by one, until you find the right one.
Objective
Our goal is to write a C program that:
Accepts a list of integers (your friends’ numbers).
Accepts a target value (the friend you want to find).
Uses Linear Search to check each one.
Displays the position if found, or a message if not found.
Code:
#include <stdio.h> int main() { int numbers[100]; // Array to store numbers int totalElements; // Total number of elements in the array int index; // Loop counter int targetValue; // The value to search for int isFound = 0; // Flag to indicate if target was found // Input: Total number of elements printf("Enter the number of elements in the array: "); scanf("%d", &totalElements); // Input: Elements of the array printf("Enter %d elements:\n", totalElements); for(index = 0; index < totalElements; index++) { scanf("%d", &numbers[index]); } // Input: The value to be searched printf("Enter the value to search: "); scanf("%d", &targetValue); // Linear Search Logic for(index = 0; index < totalElements; index++) { if(numbers[index] == targetValue) { printf("Value %d found at position %d.\n", targetValue, index + 1); isFound = 1; break; } } // Output if value not found if(!isFound) { printf("Value %d not found in the array.\n", targetValue); } return 0; }
Explanation
1. Creating the List
You ask your friends to line up and tell each one to hold a number. This is your array creation step.
2. Searching for the Target Friend
You pick the number you’re looking for (say 40). Now, you start asking each friend in line one by one “Do you have 40?”
If someone says “Yes!”, you stop there and shout,
“Found my friend at position 4!”If nobody says yes, you sadly admit,
"Friend not found.”
Output
If not found:
| ← Previous | 🏠 Homepage | Next Chapter → |
No comments:
Post a Comment