blob: 41004ad50a2600c323e3f1aabb71527f1c242484 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
#include <stdio.h>
#define OUTWORD 0
#define INWORD 1
#define MAXWORDLEN 30
int longest(const int *list) {
int max = 0;
int length = sizeof list / sizeof *list;
for (int i = 0; i < length; i++){
if (list[i] > max) max = list[i];
}
return max;
}
void usage() {
printf("print a histogram of the lengths of words in stdin (K&R ex 1-13)\n");
printf(" vertical axis is frequency\n");
printf(" horizontal axis is word length\n");
}
int main (int argc, char *argv[]) {
if (argc > 1) { usage(); return 0;}
int c, i, j, wordlen;
int ndigit[MAXWORDLEN] = {0};
wordlen = 0;
char state = OUTWORD;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
if (state == INWORD) ++ndigit[wordlen];
wordlen = 0;
state = OUTWORD;
}
else {
state = INWORD;
++wordlen;
}
}
int max = longest(&ndigit);
// i counts down from the top to the bottom
// (actually from a couple above the top, for padding)
// we start printing each bar as i gets to be within the bar's value
for (i = max + 2; i > 0; i--) {
// side axis
printf("%2d |", i);
for (int j = 0; j < MAXWORDLEN; ++j)
printf(" %s ", i <= ndigit[j] ? "=" : " ");
printf("\n");
}
// bottom axis
printf(" +");
for (j = 0; j < MAXWORDLEN; ++j)
printf("-|-");
printf("\n |");
for (j = 0; j < MAXWORDLEN; ++j)
printf("%3d", j);
printf("\n");
return 0;
}
|