Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Exercise 1-13.
- * Write a program to print a histogram of the lengths of words in its input.
- * It is easy to draw the histogram with the bars horizontal; a vertical
- * orientation is more challenging.
- */
- #include <stdio.h>
- #define IN 1 /* inside a word */
- #define OUT 0 /* outside a word */
- #define MAXLEN 64
- #define HWIDTH 80
- /* count lines, words, and characters in input */
- main() {
- int c, state, i;
- int wlen[MAXLEN], len, max;
- state = OUT;
- len = 0;
- for (i = 0; i < MAXLEN; i++)
- wlen[i] = 0;
- max = 0;
- while ((c = getchar()) != EOF) {
- if (c == ' ' || c == '\n' || c == '\t') {
- if (state == IN) {
- state = OUT;
- /* we need to consider this word */
- if (len < MAXLEN) {
- ++wlen[len];
- }
- len = 0;
- }
- } else {
- state = IN;
- ++len;
- }
- }
- for (i = 0; i < MAXLEN; i++)
- if (wlen[i] > max)
- max = wlen[i];
- for (i = 0; i < MAXLEN; i++) {
- if (wlen[i]) {
- printf("%2d ", i);
- for (len = 0; len < (wlen[i]*HWIDTH)/max; len++)
- putchar('@');
- for (len = 0;
- len < HWIDTH - (wlen[i]*HWIDTH)/max; len++)
- putchar(' ');
- printf(" %6d\n", wlen[i]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement