From 86624a9e6d2baaedd5a1b8dd4e5412216cfc635a Mon Sep 17 00:00:00 2001 From: Zhineng Li Date: Sat, 10 Jan 2026 18:10:47 +0800 Subject: add exercise 1-13: vertical version of histogram --- ch01/ex13-vhistogram.c | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 ch01/ex13-vhistogram.c (limited to 'ch01') diff --git a/ch01/ex13-vhistogram.c b/ch01/ex13-vhistogram.c new file mode 100644 index 0000000..9182500 --- /dev/null +++ b/ch01/ex13-vhistogram.c @@ -0,0 +1,66 @@ +#include + +#define IN 1 /* inside a word */ +#define OUT 0 /* outside a word */ + +#define INDICATOR_BAR '#' +#define INDICATOR_EMPTY ' ' + +/* print a vertical histogram of word lengths */ +int main() +{ + int c, i, j, k, nc, state; + int nlen[10]; + int maxlen; + + for (i = 0; i < 10; ++i) + nlen[i] = 0; + + maxlen = 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; + ++nlen[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; + ++nlen[i]; + nc = 0; + } + + for (i = 0; i < 10; ++i) + if (nlen[i] > maxlen) + maxlen = nlen[i]; + + for (i = 0; i < maxlen; ++i) { + for (j = 0; j < 10; ++j) { + k = maxlen - i - 1; + if (k < nlen[j]) + printf("%3c", INDICATOR_BAR); + else + printf("%3c", INDICATOR_EMPTY); + } + putchar('\n'); + } + + for (i = 0; i < 10; ++i) + if (i == 9) + printf(" >9"); + else + printf("%3d", i + 1); + putchar('\n'); +} -- cgit v1.2.3