🔍Let’s Find It – Linear Search! 🎯

let’s-find-it-–-linear-search!-

🍫 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:

Image description

📢 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 
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;
}

🖥️ 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 🚀

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
the-nonobvious-link-between-business-agility-and-ai-readiness

The Nonobvious Link Between Business Agility and AI Readiness

Next Post
how-to-develop-a-hipaa-compliant-app:-a-complete-guide

How to Develop a HIPAA-Compliant App: A Complete Guide

Related Posts