summaryrefslogtreecommitdiff
path: root/ch01/ex13-histogram.c
blob: 14002a56c46d5f1128c63d0542948ee04fe85d3e (plain)
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
#include <stdio.h>

#define IN  1    /* inside a word */
#define OUT 0    /* outside a word */

/* print a histogram of word lengths */
int main()
{
	int c, i, j, nc, state;
	int ndigit[10];

	for (i = 0; i < 10; ++i)
		ndigit[i] = 0;

	nc = 0;
	state = OUT;
	while ((c = getchar()) != EOF) {
		if (c == ' ' || c == '\n' || c == '\t') {
			if (state == IN) {
				i = nc - 1;
				if (i > 9)
					i = 9;
				++ndigit[i];
				nc = 0;
			}
			state = OUT;
		} else if (state == OUT) {
			state = IN;
		}

		if (state == IN)
			++nc;
	}

	if (state == IN) {
		i = nc - 1;
		if (i > 9)
			i = 9;
		++ndigit[i];
		nc = 0;
	}

	for (i = 0; i < 10; ++i) {
		if (i == 9)
			printf(" >9: ");
		else
			printf(" %2d: ", i + 1);
		for (j = 0; j < ndigit[i]; ++j)
			putchar('#');
		putchar('\n');
	}
}