22.10.25

4. Linear Search on Words in C


hello everyone 

Let’s Search for Words, What if instead of numbers, your friends hold name cards like “apple,” “banana,” or “mango”? 

You can now search through these word friends too!

This program searches for strings (words) using the same Linear Search idea just with a little twist using strcmp() for comparison.

How It Works 

  • All your friends (numbers) line up.

  • You shout out a number you’re looking for.

  • Each friend checks their card and replies until someone says, “I’ve got it!”

  • When the round ends, you can choose to play again or call it a night.

That’s how this program uses a loop and the strcmp() function to make the search repeatable and interactive.

Code:

 #include <stdio.h>
 #include <string.h>
 
 int main() {
     char words[100][100];          // Array to store words
     char searchWord[100];          // Word to search for
     int totalWords;                // Total number of words
     int position;                  // Loop counter
     int isFound;                   // Flag to check if word found
     char choice[10];               // To store yes/no answer
 
     printf("Enter the number of words: ");
     scanf("%d", &totalWords);
 
     printf("Enter %d words:\n", totalWords);
     for(position = 0; position < totalWords; position++) {
         scanf("%s", words[position]);
     }
 
     do {
         isFound = 0;
         printf("Enter the word to search: ");
         scanf("%s", searchWord);
 
         for(position = 0; position < totalWords; position++) {
             if(strcmp(words[position], searchWord) == 0) {
                 printf("Word '%s' found at position %d.\n", searchWord, position + 1);
                 isFound = 1;
                 break;
             }
         }
 
         if(!isFound) {
             printf("Word '%s' not found in the list.\n", searchWord);
         }
 
         printf("Do you want to search again? (yes/no): ");
         scanf("%s", choice);
 
     } while(strcmp(choice, "yes") == 0 || strcmp(choice, "YES") == 0);
 
     printf("Okay, exiting the search.\n");
     return 0;
 }

Output:

  
← Previous 🏠 Homepage Next Chapter →

No comments:

Post a Comment

rating System

Loading...

A Friendship Story of Learning Data Structures with C

Sr. No. DSU BLOGS CHAPTERS 1 Array Operations in C, The Group of Friendship (Create, Insert, Delete ...