word-length-histogram.c (1995B)
1 #include <stdio.h> 2 3 #define IN_WORD 0 4 #define OUT_WORD 1 5 #define MAX_WORD_LENGTH 20 6 7 int main(){ 8 9 char c; 10 int status = OUT_WORD; 11 int wordLengths [MAX_WORD_LENGTH]; 12 int currentLength = 0; 13 14 for(int i = 0 ; i < MAX_WORD_LENGTH; ++i){ 15 wordLengths[i] = 0; 16 } 17 18 while((c = getchar()) != EOF){ 19 if(status == OUT_WORD){ 20 if(c != ' ' && c != '\t' && c != '\n'){ 21 status = IN_WORD; 22 currentLength = 1; 23 } 24 } 25 else{ 26 if(c == '\t' || c == '\n' || c == ' '){ 27 status = OUT_WORD; 28 // if it's too long, just don't count it. 29 if (currentLength < MAX_WORD_LENGTH){ 30 wordLengths[currentLength] += 1; 31 } 32 33 } 34 else{ 35 currentLength += 1; 36 } 37 } 38 39 } 40 41 if (currentLength != 0){ 42 // if it's too long, just don't count it. 43 if (currentLength < MAX_WORD_LENGTH){ 44 wordLengths[currentLength] += 1; 45 } 46 currentLength = 0; 47 } 48 49 // horizontal print 50 //for(int i = 0 ; i < MAX_WORD_LENGTH; ++i){ 51 // printf("\n%5d: ", i); 52 // for(int x = 0 ; x < wordLengths[i] ; ++x){ 53 // printf("x"); 54 // } 55 //} 56 //printf("\n"); 57 58 59 60 // vertical print 61 62 int max = 0; 63 for(int i = 0 ; i < MAX_WORD_LENGTH; ++i){ 64 if(wordLengths[i] > max){ 65 max = wordLengths[i]; 66 } 67 } 68 69 int current = max; 70 71 for(int i = max ; i > 0; --i){ 72 printf("\n"); 73 for(int x = 0 ; x < MAX_WORD_LENGTH; ++x){ 74 if(wordLengths[x] > i){ 75 char p = 'x'; 76 printf("%3c", p); 77 } 78 else{ 79 char p = ' '; 80 printf("%3c", p); 81 } 82 } 83 } 84 printf("\n"); 85 86 for(int x = 0 ; x < MAX_WORD_LENGTH; ++x){ 87 printf("%3d", x); 88 } 89 90 91 printf("\n"); 92 93 94 return 0; 95 }