From 93e7fd1dba8a971718c085c2dee85d1e31981dea Mon Sep 17 00:00:00 2001 From: Zhineng Li Date: Fri, 16 Jan 2026 07:05:08 +0800 Subject: add exercise 1-14: histogram of frequencies of characters --- ch01/ex14-histogram.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 ch01/ex14-histogram.c (limited to 'ch01/ex14-histogram.c') diff --git a/ch01/ex14-histogram.c b/ch01/ex14-histogram.c new file mode 100644 index 0000000..6d410e1 --- /dev/null +++ b/ch01/ex14-histogram.c @@ -0,0 +1,30 @@ +#include + +#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'); + } + } +} -- cgit v1.2.3