# K & R C Programs Exercise 6-4.

K and R C, Solution to Exercise 6-4:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write a C Program that prints the distinct words in its input sorted into decreasing order of frequency of occurrence. Precede each word by its count. Read more about C Programming Language .

`/************************************************************ You can use all the programs on  www.c-program-example.com* for personal and learning purposes. For permissions to use the* programs for commercial purposes,* contact info@c-program-example.com* To find more C programs, do visit www.c-program-example.com* and browse!* *                      Happy Coding***********************************************************/#include<stdio.h>#include<ctype.h>#define MAXWORD 100#define NDISTINCT 1000struct tnode(  char *word;int count;struct tnode *addtree(struct tnode *, char *);int getword(char *, int);void sortlist(void);void treestore(struct tnode *);struct tnode *list[DISTINCT];int ntn = 0;/* print distinct words sorted in decreasing order of freq.*/main(){ struct tnode *root; char word[MAXWORD]           int i; root = NULL; while(getword(word, MAXWORD) != EOF)  if(isalpha(word[0]))   root = addtree(root, word); treestore(root); sortlist(); for(i = 0;i < ntn; i++)  printf("%2d:%20sn",list[i]->count,list[i]->word); return 0;}//getword: get next word or character from inputint getword(char *word, int lim){ int c, d, comment(void), getch(void); void ungetch(int); char *w = word; while(isspace(c = getch()))  ; if(c !=EOF)  *w++ = c; if(isalpha(c) || c == '-' || c == '#'){  for(; --lim > 0; w++)   if(!isalnum(*w = getch()) && *w != '-') {    ungetch(*w);    break;   } } else if(c == ''' || c == '\'){  for( ; --lim > 0; w++)   if(((*w = getch()) == '\')     *++w = getch();   else if(*w == c) {    w++;    break;   }else if(*w == EOF)    break; }else if(c == '/')  if((d = getch()) == '*')   c = comment();  else   ungetch(d); *w = ''; return c;}//comment: skip over comment and return a characterint comment(){ int c; while((c = getch()) != EOF)  if(c == '*')   if((c = getch()) == '/')    break;   else    ungetch(c); return c;}//TREESTORE:STORE IN LIST[] POINTERS TO TREE NODESvoid treestore(struct tnode *p){ if(p != NULL) {  treestore(p->left);  if(ntn < NDISTINCT)   list[ntn++] = p;  treestore(p->right); }}//sortlist: sort list of pointers to tree nodesvoid sortlist(){ int gap, i,j; struct tnode *temp; for(gap = ntn/2;gap > 0;gap /= 2)  for(i = gap; i < ntn;i++)   for(j = i - gap;j >= 0;j -= gap) {    if((list[j]->count) >= (list[j+gap]->count))     break;    temp = list[j];    list[j] = list[j+gap];    list[j+gap] = temp;   }}`
`Read more c programsC BasicC StringsK and R C Programs Exercise`

You can easily select the code by double clicking on the code area above.