Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- /*
- cAgain12.c
- Solution for Kernighan & Ritchie, Exercise 1-13, p24.
- Write a program to print a histogram of the lengths of words in its input
- Requirements:
- find the length of each word
- count and store the number of words of each length using an array
- print the histogram
- */
- main()
- {
- //declare the variables
- int c, i, k, dots, counter;
- // maximum word length =29 chars; that's a problem for another chapter!
- int wordLength[30];
- //initialize the variables
- counter = i = k = dots = 0;
- //initialize the array
- for(i = 0; i < 30; ++i){
- wordLength[i]= 0;
- }//end for
- //get the input:
- while ((c=getchar()) !=EOF){
- //the next line of code says 'if the input is none of these characters...'
- //note: we have to escape the quotation character and backslash character
- //note: we don't include the apostrophe, because if we did
- //words like "don't" would get
- //counted as only three characters, "don"
- if (!(c == ' ' || c == '\n' || c == '\t' || c == ',' || c == '.' || c == ';' || c == '!' || c == '\"' || c == ':' || c == '/' || c == '\\'))
- // then increment the character count +1'
- ++counter;
- else { //stop counting and increment the array for that length by +1
- ++wordLength[counter];
- //reset the counter for the next word
- counter = 0;
- }//end else
- }//end while
- //print the histogram horizontally:
- printf("\n");
- printf("No of characters per word\n");
- for (i = 1; i < 30; ++i) {
- printf("\n%3i: ", i);
- dots = wordLength[i];
- for (k = 1; k <= dots; ++k){
- printf("=");
- }//end for
- }//end for
- printf("\n\n"); //create a space between the last line of output and the prompt
- }//end main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement