summaryrefslogtreecommitdiff
path: root/ch01/ex14-histogram.c
blob: 6d410e1b098dc59d7ed7a7e3eacda2ff1f205af1 (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
#include <stdio.h>

#define ASCII_FIRST_PRINTABLE_CODEPOINT 33
#define ASCII_LAST_PRINTABLE_CODEPOINT  126
#define ASCII_SPACE ASCII_LAST_PRINTABLE_CODEPOINT - ASCII_FIRST_PRINTABLE_CODEPOINT + 1

#define BAR '#'

/* print a histogram of the frequencies of different characters */
int main()
{
	int c, i, j;
	int nchar[ASCII_SPACE];

	for (i = 0; i < ASCII_SPACE; ++i)
		nchar[i] = 0;

	while ((c = getchar()) != EOF)
		if (c >= ASCII_FIRST_PRINTABLE_CODEPOINT && c <= ASCII_LAST_PRINTABLE_CODEPOINT)
			++nchar[c - ASCII_FIRST_PRINTABLE_CODEPOINT];

	for (i = 0; i < ASCII_SPACE; ++i) {
		if (nchar[i] > 0) {
			printf("%c: ", i + ASCII_FIRST_PRINTABLE_CODEPOINT);
			for (j = 0; j < nchar[i]; ++j)
				putchar(BAR);
			putchar('\n');
		}
	}
}