July 28, 2011
Ex 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.

#include<stdio.h>

#define IN 1
#define OUT 0
#define MAXLEN 10

main()
{
        int c, state, nc;
        int i, j, k, p;
        int cnt[MAXLEN];

        state = OUT;
        nc = 0;

        for(i = 0; i < MAXLEN; i++)
                cnt[i] = 0;

        while((c = getchar()) != EOF){
                if(c == ‘\n’ || c == ’ ’ || c == ‘\t’)
                        if(state == IN){
                                state = OUT;
                                ++cnt[nc];

Input:

hello hello
i i i
el el el
world world world world
input (END)

Output:

        1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
    +——————————————————————————————-
  1 |   * * *
  2 |   * * *
  3 |  
  4 |  
  5 |   * * * * * *
  6 |  
  7 |  
  8 |  
  9 | 

1:49am  |   URL: http://tmblr.co/Zi3hLy7cVDNP
Filed under: K&amp;R