Monday, December 8, 2014

Program in C to count the number of words.


The problem to find the number of words as present in a piece of inputted text is one of the basic problems encountered while learning the C language.

The internet is flooded with probable programs written in C to solve it , but , they fail miserably when tested with conditions like :

1)Presence of multiple ,  unwanted spaces between any two consecutive words.
2)Presence of trailing spaces after the end of text ,that might have crept in erroneously.

As a result of the above two , the output of most such programs goes awry .

The following program , however , does not fall into that trap and gives accurate results for the above two and other such similar cases.


Program without Comments:


/*Program to count the number of words in an inputted text.*/
#include<stdio.h>
int main(){
int words=0;
int space=0;
int i=0;
char s[200];
printf("ENTER YOUR TEXT , TO END THE INPUT HIT ENTER KEY \n");
scanf("%[^\n]s",s);
while(s[i]!='\0'){
if(s[i]==' ' && space==0){
      ++space;    
     ++words;
          }else{
          if(s[i]==' '){;}else{
          space=0;
          }
++i;
          }
          }
if(s[i-1]==' '){--words;}         
printf("THE NUMBER OF WORDS IS : %d",words+1);
return 0;
}




Program with Comments:


/*Program to count the number of words in an inputted text.*/
#include<stdio.h>
int main(){
int words=0;
int space=0;
int i=0;
char s[200];
printf("ENTER YOUR TEXT , TO END THE INPUT HIT ENTER KEY \n");
scanf("%[^\n]s",s); 
/*We'll scan the text till the ENTER Key is pressed.*/ while(s[i]!='\0'){    /*Check to determine the end of char array*/
if(s[i]==' ' && space==0){ /*Determine if this is the first encountered space*/
      ++space;       /*If yes , then increase the space counter by 1 */
     ++words;            /*We just passed by a word , hence increase word count by 1*/
          }else{
          if(s[i]==' ')/*If s[i] was a space AND space>0 , that means we are still passing by more and more spaces ,hence do nothing till we reach a non-space character.*/{;}else{
          space=0; /*If not ,then that means we are traversing inside a word :),hence simply put space=0  , this word's presence would be counted once we encounter a space after this , as done in the top part of the loop*/
          }
++i; /*Increment the Index counter to traverse the next character */
          }
          }
if(s[i-1]==' '){--words;}   /*Check presence of any trailing spaces after the last word in the inputted text , as in that case the second last element would contain a space , hence check if s[i-1]==' ' , if it is , then , for sure our loop would have increased the count of words by 1 , hence reduce it by 1 to get correct result.*/      
printf("THE NUMBER OF WORDS IS : %d",words+1); /*Finally print the number of words.*/
return 0;
}

No comments:

Post a Comment