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");
}
TrustyTony commented: Neat code inspite of bug +13

Recommended Answers

All 3 Replies

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.

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

commented: Thanks. +1

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.