From 49891f6bce29843f503b437c84d83cb787ecfa87 Mon Sep 17 00:00:00 2001 From: Zhineng Li Date: Sat, 10 Jan 2026 16:37:39 +0800 Subject: first commit --- ch01/ex13-histogram.c | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 ch01/ex13-histogram.c (limited to 'ch01/ex13-histogram.c') diff --git a/ch01/ex13-histogram.c b/ch01/ex13-histogram.c new file mode 100644 index 0000000..14002a5 --- /dev/null +++ b/ch01/ex13-histogram.c @@ -0,0 +1,52 @@ +#include + +#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'); + } +} -- cgit v1.2.3