Blob


1 /* Write a program to print a histogram of the lengths of words in
2 * its input. It is easy to draw the histogram with the bars horizontal;
3 * a vertical orientation is more challenging. */
5 #include <stdio.h>
6 #define MAXLENGTH 20
8 main()
9 {
10 int histogram[MAXLENGTH+1], letters, c, maxfreq;
12 for (int i = 1; i <= MAXLENGTH; ++i)
13 histogram[i] = 0;
14 letters = 0;
15 maxfreq = 0;
17 while ((c = getchar()) != EOF) {
18 if (c == ' ' || c == '\t' || c == '\n') {
19 ++histogram[letters];
20 letters = 0;
21 } else {
22 ++letters;
23 }
24 }
25 ++histogram[letters];
27 for (int i = 1; i <= MAXLENGTH; ++i) {
28 printf("%2d: %5d", i, histogram[i]);
29 for (int j = 0; j < histogram[i]; ++j) {
30 printf("=");
31 }
32 printf("\n");
34 maxfreq = (histogram[i] > maxfreq ? histogram[i] : maxfreq);
35 }
36 printf("\n\n");
37 for (int h = maxfreq; h > 0; --h) {
38 for (int i = 1; i <= MAXLENGTH; ++i) {
39 if (histogram[i] >= h) {
40 printf(" | ");
41 } else {
42 printf(" ");
43 }
44 }
45 printf("\n");
46 }
47 for (int i = 1; i <= MAXLENGTH; ++i) {
48 printf("===");
49 }
50 printf("\n");
51 for (int i = 1; i <= MAXLENGTH; ++i) {
52 printf("%2d ",i);
53 }
54 printf("\n");
55 }