diff options
| author | Zhineng Li <[email protected]> | 2026-01-16 07:05:08 +0800 |
|---|---|---|
| committer | Zhineng Li <[email protected]> | 2026-01-16 07:06:47 +0800 |
| commit | 93e7fd1dba8a971718c085c2dee85d1e31981dea (patch) | |
| tree | f5ef29f6de3764e585d21f05d1d0df65d282b8e0 | |
| parent | 20d3661062b7b42fcfa91cc9b43f2a6752804e62 (diff) | |
| download | c-knr-exercises-93e7fd1dba8a971718c085c2dee85d1e31981dea.tar.gz c-knr-exercises-93e7fd1dba8a971718c085c2dee85d1e31981dea.zip | |
add exercise 1-14: histogram of frequencies of characters
| -rw-r--r-- | ch01/ex14-histogram.c | 30 |
1 files changed, 30 insertions, 0 deletions
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 <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'); + } + } +} |
