Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #define LIMIT 20
  3. #define IN 1
  4. #define OUT 0
  5.  
  6. int main(void)
  7. {
  8.  
  9.     /*
  10.      * The freq array will be used to store a frequency of values associated to a natural
  11.      * number from 1 to 20 included. The word variable indicates whether the c variable
  12.      * currently holds a value that is inside or outside of a word. The count variable
  13.      * keeps count of the current number of characters inside the word we're evaluating.
  14.      * The toolong variable is just there to prevent a segfault in case the word exceeds
  15.      * the number of elements included in the freq array, so that we don't increment
  16.      * a nonexistent value.
  17.     */
  18.     char c;
  19.     int freq[LIMIT];
  20.     for (int i = 0; i <= LIMIT; ++i) freq[i] = 0;
  21.     int word = OUT;
  22.     int count = 0;
  23.     int toolong = 0;
  24.  
  25.     /*
  26.      * Evaluate the current character's ASCII value:
  27.      * 1) If it's neither an uppercase nor a lowercase letter, then it's not a word.
  28.      * if the number of letters in the current word doesn't exceed the limit,
  29.      * then increment the freq array's element corresponding to that word's length.
  30.      * 2) If we're not currently inside a word, yet the ASCII value of the current char
  31.      * corresponds to a letter, then we've just entered a word. Bring the counter back to zero.
  32.     */
  33.     while ((c = getchar()) != EOF) {
  34.         if ((c < 'A' || c > 'z') || (c > 'Z' && c < 'a')) {
  35.             word = OUT;
  36.             if (count <= LIMIT) ++freq[count];
  37.             else ++toolong;
  38.         }
  39.         else if (word == OUT) {
  40.             word = IN;
  41.             count = 0;
  42.         }
  43.         ++count;
  44.     }
  45.  
  46.     /*
  47.      * Prints all natural numbers from 1 to 20, and next to each number, prints one
  48.      * '*' character for every instance of a word containing that number of characters.
  49.      * Then, print the number of words that were too long to be taken into account.
  50.     */
  51.     for (int i = 1; i <= LIMIT; ++i) {
  52.         printf("| %2d | ", i);
  53.         for (int f = 1; f <= freq[i]; ++f) printf("*");
  54.         putchar('\n');
  55.     }
  56.     printf("Number of words that were too long to be taken into account: %d\n", toolong);
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement