DEV Community

Khushi
Khushi

Posted on • Edited on

πŸ”Linear Search Made Easy – Find Like a Detective!

🍫 A Chocolate Hunt Story
Imagine you're hungry (like really hungry πŸ˜‹) and craving your favorite chocolate...
You open your snack box, and here’s what you see:[KitKat, Dairy Milk, Munch, Perk, 5-Star]
Now, you don’t know where Dairy Milk is, so what do you do?
πŸ‘‰ Start checking one by one!
KitKat? β†’ ❌ Nope
Dairy Milk? β†’ βœ… Yesss! Found it

That's exactly what Linear Search does in coding too!
🧠 What is Linear Search?
Linear Search is like going through each item one-by-one until you find the one you want.
No shortcuts. No tricks. Just pure checking β€” start to end! πŸšΆβ€β™€οΈ

πŸ’‘Real Example :
Let's say you have:
arr = [10, 25, 30, 45, 50]
target = 30

We want to find the number 30.
Let’s dry run this:

πŸ“’ Result: Found at index 2.

❓ What if it’s not there?
arr = [10, 25, 30, 45, 50]
target = 100

We check all… and nope! It’s not there
πŸ‘‰ In that case, we return -1 (means "Not Found").

πŸ“Œ Simple Steps to Remember:

  • Start from the first item
  • Check: Is this the one?
  • If yes β†’ πŸŽ‰ return the index!
  • If not β†’ move to next
  • Repeat until: You find the item βœ”οΈ Or reach the end ❌ (return -1)

πŸ§‘β€πŸ’»Code Time! (C++)

#include <iostream>
using namespace std;
int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i; // Found!
        }
    }
    return -1; // Not found
}
int main() {
    int chocoBox[] = {4, 8, 15, 23, 42};
    int size = sizeof(chocoBox) / sizeof(chocoBox[0]);
    int myFavorite = 23;
     int result = linearSearch(chocoBox, size, myFavorite);
     if (result != -1)
       cout << "Yay! Found your favorite chocolate at position: " << result;
    else
        cout << "Oops! Your chocolate isn't in the box!" << endl;
        return 0;
}

Enter fullscreen mode Exit fullscreen mode

πŸ–₯️ Output :Yay! Found your favorite chocolate at position: 3

πŸ’¬ Wrapping Up
Linear Search = The simplest way to find something β€” one step at a time.
No rocket science. Just like finding your Dairy Milk 🍫 in a snack box!
Want more fun DSA stuff like this daily?
✨ Follow me β€” I’m Khushi, a fellow learner sharing daily bite-sized DSA logic, patterns & stories πŸ’›
Let’s learn & grow together πŸš€

Top comments (0)