954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Histogram of the length of words exercise hint?

Hello.

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 some code, but when I start the program, it doesn't do anything.

I can't figure out where I'm wrong, and this exercise has drained me.

Can anyone give me a hint on where I'm going wrong. And please don't post solutions, I just need some hints on how to solve this.

#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");
}
ak24
Newbie Poster
17 posts since Dec 2010
Reputation Points: 23
Solved Threads: 0
 

On line 22 you are setting space to 1 when you increase the length. I'm pretty sure if you take that line out you should be good.

sfuo
Practically a Master Poster
656 posts since Jul 2009
Reputation Points: 164
Solved Threads: 99
 

and how would the lines 16 to 18 would then be executed? Variable i is not reset in while loop.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 
and how would the lines 16 to 18 would then be executed? Variable i is not reset in while loop.

Thank you!

I thought variable i was 0.

Problem solved.

ak24
Newbie Poster
17 posts since Dec 2010
Reputation Points: 23
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You