Advertisement
applehelpwriter

Kernighan & Ritchie Solution 1-13

Aug 25th, 2013
426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.81 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. /*
  4. cAgain12.c
  5.  
  6. Solution for Kernighan & Ritchie, Exercise 1-13, p24.
  7.  
  8. Write a program to print a histogram of the lengths of words in its input
  9.  
  10. Requirements:
  11.     find the length of each word
  12.     count and store the number of words of each length using an array
  13.     print the histogram
  14.    
  15. */
  16.  
  17. main()
  18. {
  19.  
  20. //declare the variables
  21. int c, i, k, dots, counter;
  22.  
  23. // maximum word length =29 chars; that's a problem for another chapter!
  24. int wordLength[30];
  25.  
  26. //initialize the variables
  27. counter = i = k = dots = 0;
  28.  
  29. //initialize the array
  30. for(i = 0; i < 30; ++i){
  31.     wordLength[i]= 0;
  32. }//end for
  33.  
  34. //get the input:
  35. while ((c=getchar()) !=EOF){
  36.    
  37.     //the next line of code says 'if the input is none of these characters...'
  38.     //note: we have to escape the quotation character and backslash character
  39.     //note: we don't include the apostrophe, because if we did
  40.     //words like "don't" would get
  41.     //counted as only three characters, "don"
  42.    
  43.     if (!(c == ' ' || c == '\n' || c == '\t' || c == ',' || c == '.' || c == ';' || c == '!' || c == '\"' || c == ':' || c == '/' || c == '\\'))
  44.    
  45.     // then increment the character count +1'
  46.         ++counter;
  47.    
  48.     else {  //stop counting and increment the array for that length by +1
  49.    
  50.         ++wordLength[counter];
  51.  
  52.         //reset the counter for the next word
  53.     counter = 0;
  54.     }//end else
  55.    
  56. }//end while
  57.  
  58.  
  59. //print the histogram horizontally:
  60.  
  61. printf("\n");
  62. printf("No of characters per word\n");
  63.  
  64. for (i = 1; i < 30; ++i) {
  65.     printf("\n%3i: ", i);
  66.     dots = wordLength[i];
  67.         for (k = 1; k <= dots; ++k){
  68.         printf("=");
  69.        
  70.         }//end for
  71.        
  72.    
  73. }//end for
  74.  
  75.  
  76. printf("\n\n"); //create a space between the last line of output and the prompt
  77.  
  78. }//end main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement