#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:
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.
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.
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.
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.
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..