1

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");
}
Votes + Comments
Neat code inspite of bug
3
Contributors
3
Replies
9
Views
6 Years
Discussion Span
Last Post by ak24
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.

1

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

Edited by pyTony: n/a

Votes + Comments
Thanks.
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.