6.23
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.
Notice: I provided a simple version than the method in <<The C Answer Book>>.
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
#define N 11 /* length of a word*/
#define LENMAX 10 /* max length of a word we condiering*/
/* count words in input */
int main(void)
{
int i,c, len;
int count[N];
long thisval = 0;
long maxval = 0;
int thisidx = 0;
len = 0;
for( i = 0; i < N; i++)
count[i] = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '/n' || c == '/t')
{
if((len > 0) && (len <= 10))
{
thisval = ++count[len-1];
if(thisval > maxval)
{
maxval = thisval;
}
}
else if(len >= N)
{
thisval = ++count[N-1];
if(thisval > maxval)
{
maxval = thisval;
}
}
len = 0;
continue;
}
else
++len;
}
/*draw the histogram*/
for(thisval = maxval; thisval > 0; thisval--)
{
printf("%4d | ", thisval);
for(thisidx = 0; thisidx <= LENMAX; thisidx++)
{
if(count[thisidx] >= thisval)
{
printf("* ");
}
else
{
printf(" ");
}
}
printf("/n");
}
printf(" +");
for(thisidx = 0; thisidx <= LENMAX; thisidx++)
{
printf("---");
}
printf("/n ");
for(thisidx = 0; thisidx < LENMAX; thisidx++)
{
printf("%2d ", thisidx + 1);
}
printf(">%d/n", LENMAX);
}