diff options
| author | Zhineng Li <[email protected]> | 2026-01-10 18:10:47 +0800 |
|---|---|---|
| committer | Zhineng Li <[email protected]> | 2026-01-10 18:10:47 +0800 |
| commit | 86624a9e6d2baaedd5a1b8dd4e5412216cfc635a (patch) | |
| tree | b66e57866c91cf355436e446282958eaa76d43bb | |
| parent | 49891f6bce29843f503b437c84d83cb787ecfa87 (diff) | |
| download | c-knr-exercises-86624a9e6d2baaedd5a1b8dd4e5412216cfc635a.tar.gz c-knr-exercises-86624a9e6d2baaedd5a1b8dd4e5412216cfc635a.zip | |
add exercise 1-13: vertical version of histogram
| -rw-r--r-- | ch01/ex13-vhistogram.c | 66 |
1 files changed, 66 insertions, 0 deletions
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 <stdio.h> + +#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'); +} |
