#include <stdio.h>
#include <ctype.h>

// Function to count the words in a given sentence
int countWords(char str[]) 
{
    int count = 0;   // This will store the word count
    int inWord = 0;  // This will check if we are inside a word (flag)

    // Loop through each character of the string until we hit the null terminator ('\0')
    for (int i = 0; str[i] != '\0'; i++) 
{
        // Check if the current character is a space or punctuation (i.e., word separator)
        if (isspace(str[i])) 
{
            inWord = 0; // We are outside a word now
        } 
else if (inWord == 0) 
{
            // We've encountered a non-space character (a new word)
            inWord = 1; // Set flag to indicate we're inside a word
            count++;    // Increment the word count
        }
    }
    return count; // Return the total word count
}

int main() 
{
    char sentence[100]; // Array to store the sentence
    printf("Enter a sentence: ");
    fgets(sentence, sizeof(sentence), stdin); // Input sentence from the user

    // Call the countWords function and display the result
    int wordCount = countWords(sentence);
    printf("The number of words in the sentence: %d\n", wordCount);
    return 0;
}

Explanation:

  1. Libraries:
    • We include the stdio.h library for input and output functions like printf and fgets.
    • The ctype.h library is used to work with character functions like isspace(), which checks if a character is a space or a whitespace.
  2. Function: countWords:
    • This function takes a string (char str[]) and loops through each character to count words.
    • We maintain two variables: count to keep track of the number of words, and inWord to check if we are currently inside a word.
    • The loop checks if the current character is a space or not. If it’s not a space and we aren’t already inside a word, we count it as the start of a new word.
  3. Word Definition:
    • A word is defined as any sequence of characters separated by spaces or punctuation. So, the function counts words based on this condition.
  4. Input Handling:
    • The user is prompted to input a sentence using fgets(). This function is safer than gets() as it prevents buffer overflows by limiting input to the size of the array.
  5. Main Function:
    • The program calls the countWords() function with the user’s input and displays the result.
Enter a sentence: Hello world, this is a test sentence.
The number of words in the sentence: 7

Input:

  • "Hello world, this is a test sentence."

Explanation of Output:

  • The input sentence has seven words: Hello, world,, this, is, a, test, sentence..

Leave a Reply

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

Verified by MonsterInsights