## Problem Statement:

Exercise 1-13: Write a program to print a histogram of the lengths of words in input. It is easy to draw the histogram with bars horizontal; a vertical orientation is more challenging.

## Solution:

Horizontal histogram is already covered here. Counting part of the program remains the same. We need to print the same counts in Vertically. Program explains itself.

#include <stdio.h>

/* intenal states to count words */
#define IN 1
#define OUT 0

#define MAX_WORD_LEN 20

int main()
{
int count[MAX_WORD_LEN] = {0};
int c, len = 0, max = 0;
int state = OUT;
int i = 0, j = 0;

while((c = getchar()) != EOF) {
if(c == ' ' || c == '\t' || c == '\n') {
if(state == IN && len >= 1 &&
len < MAX_WORD_LEN) {
count[len]++;
if(count[len] > max) {
max = count[len];
}
}
len = 0;
state = OUT;
}else if(state == OUT) {
state = IN;
len++;
}else {
len++;
}
}

printf("\n");
/* Draws the histogram */
for(i = max; i >= 1; i--) {
for(j = 1; j <= MAX_WORD_LEN; j++) {
if(count[j] > i) {
printf("  *");
}else {
printf("   ");
}
}
printf("\n");
}
/* Draws a verticle line */
for(j = 1; j <= MAX_WORD_LEN; j++) {
printf("---");
}
printf("\n");
/* Print the counts */
for(j = 1; j <= MAX_WORD_LEN; j++) {
printf("%3d", j);
}
printf("\n");

return 0;
}

Output of the above program looks as follows

$cat mary Mary had a little lamb Little lamb, little lamb Mary had a little lamb Its fleece was white as snow And everywhere that Mary went Mary went, Mary went Everywhere that Mary went The lamb was sure to go He followed her to school one day School one day, school one day He followed her to school one day Which was against the rule It made the children laugh and play Laugh and play, laugh and play It made the children laugh and play To see a lamb at school And so the teacher turned him out Turned him out, turned him out And so the teacher turned him out But still he lingered near And waited patiently Patiently, patiently And wai-aited patiently Til Mary did appear Mary had a little lamb Little lamb, little lamb Mary had a little lamb Its fleece was white as snow And everywhere that Mary went Mary went, Mary went Everywhere that Mary went The lamb was sure to go$ ./a.out < mary

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


Next Article - K & R : Exercise 1.14 - character vertical histogram
Previous Article - K & R : Exercise 1.13 - Horizontal histogram [Part 1]
All Article - K & R Answers