ckernighan-and-ritchie

Histogram of the length of words exercise hint?


I'm learning C with "The C Programming Language" book, and I'm trying to solve 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."

I wrote the code, but when I press CTRL+Z (End-of-File), it shows all zeros instead of the length of words.

Could anyone give me a hint on where I'm going wrong?

#include <stdio.h>

/* print a histogram of the length of words from input */
main()
{
    int c, i, wordn, space;
    int lengthn[20];

    wordn = space = 0;
    for (i = 0; i < 20; ++i)
        lengthn[i] = 0;

    while ((c = getchar()) != EOF) {
        if (c == ' ' || c == '\t' || c == '\n')
            if (space == 1) {
                ++wordn;
                space = 0;
                ++i;
            }
        if (c != ' ' && c != '\t' && c != '\n') {
            ++lengthn[i];
            space = 1;
        }
    }
    printf("Length: ");
    for (i = 0; i < 16; ++i)
        printf("%d   ", lengthn[i]);
    printf("\n        --------------------------------------------------------------\n");
    printf("Word:   1   2   3   4   5   6   7   8   9   10   11   12   13   14   15\n");
}

Solution

  • (Because the OP is asking for hints, not the solution)

    So ... what does i equal after this loop?

    for (i = 0; i < 20; ++i)
        lengthn[i] = 0;
    

    And where do you use it next?