Print a Histogram based on word lengths (C)

I suggest you simplify the problem by solving it for the case of one word per line, so you can use fgets. Here's how to "eat up" lines that are too long.

Then, as often, the central data structure is the key to solving the problem. The data structure you need is an array used as frequency table:

int freq[11];

In freq[1], store the number of words/lines of length 1, in freq[2] those of length 2, etc., and in freq[0] those of length >10. You don't need to store the words since the rest of the program only needs their length. Writing out the histogram should be easy now.

I hope this isn't too much of a spoiler.


I loved the pseudo-code! Some good thinking there, but you're still not ordering your program right.

As you said yourself, you can't read the text, go back and print an X in a particular row. If we establish that it can't be done, then there's no choice but to know all the values of the histogram beforehand.

So you should think your program as having two parts (and you'll make this kind of division in practically every program you write): first, a part that will make calculations; and then a part that will output them in a certain format (the histogram).

This tip should get you started! If you need further help, comment below.

Tags:

C