Google Add

Search

C,C++ Program to Count Number of Words


Program to Count Number of Words in a Sentence/Text



In programming string is basically an array of characters.

So first we declare string  by char str[200];

Logic

To solve this problem we run a loop from 0th index of string to the end of string. If any space is found we increment the count by 1.



#include <stdio.h>
#include <string.h>

int main()
{

  char str[200];
  int count=0,i;

   printf("Enter some text");
   gets(str); // Taking user input

   for(i=0;str[i]!='\0';i++){
        if(str[i]==' ' && str[i+1]!=' '){
            count++;
       }   
}
     printf("Number of words %d",count+1);
     return(0);
}


No comments:

Post a Comment