Signup/Sign In
PUBLISHED ON: FEBRUARY 17, 2022

C Program To Count Number Of Words In A Given Text Or Sentence

Learn C Language Tutorial

Logic to Count Number Of Words In A Given Text Or Sentence:

  • Get the input from the string and store it in the array variable,
  • Count the number of spaces between the words using the for loop,
  • Increment the count of the variable by 1 in every loop,

C Program to Count Number of Words in a given Text Or Sentence:

#include <stdio.h>
#include <string.h>
 
void main()
{
    char str[200];
    int y = 0, x;
 
    printf("Enter The String To Find The No. Of Words: \n");
    scanf("%[^\n]str", str);
    for (x = 0;str[x] != '\0';x++)
    {
        if (str[x] == ' ' && str[x+1] != ' ')
            y++;    
    }
    printf("The No. Of Words In The Given String Is: %d\n", y + 1);
}

Output:

num words



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight