Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Exercise 1-13.

Name: Anonymous 2008-12-14 18:01

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.


The horizontal version:


#include <stdio.h>

#define IN      1
#define OUT     0
#define MAX_LEN 10

int main() {
        int c, i, j, state;

        long length = 0, wlength[MAX_LEN];

        for (i = 0; i < MAX_LEN; ++i)
                wlength[i] = 0;

        while ((c = getchar()) != EOF) {
                if (c == ' ' || c == '\t' || c == '\n') {
                        if (length < MAX_LEN && state == IN)
                                ++wlength[length];
                        else if (length >= MAX_LEN && state == IN)
                                ++wlength[MAX_LEN - 1];
                        ++wlength[0];
                        length = 0;
                        state = OUT;
                }
                else {
                        ++length;
                        state = IN;
                }
        }

        if(state == IN)
                ++wlength[length];

        printf("\nno. of:\n");

        for (i = 0; i < MAX_LEN; ++i) {
                if(i == 0)
                        printf("wspace chars: ");
                else
                        printf("%i-char words: ", i);
                for (j = 1; j <= wlength[i]; ++j)
                        printf("#");
                printf("\n");
        }

        return 0;
}


:/ ?

Name: Anonymous 2008-12-14 23:18

>>3
it could be done in one line of c, too:
#include <limits.h>
#include <stdio.h>
int main(int argc, char **argv){int maxlen = 0, spaces = 0, words[LINE_MAX] = {0}; for(int c = getchar(), len = 0; !feof(stdin); c = getchar()) switch(c){ case ' ': case '\t': case '\n': ++spaces; ++words[len]; maxlen = len > maxlen ? len : maxlen; len = 0; break; default: ++len; } fputs("no. of:\nwspace chars: ", stdout); for(int i = 0; i < spaces; ++i) putchar('#'); puts(""); for(int i = 1; i <= maxlen; ++i){ printf("%d-char words: ", i); for(int j = 0; j < words[i]; ++j) putchar('#'); puts(""); } }

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List