Page 24

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 MAX_LEN 16

int main()
{
	int c;
	int num_of_len[MAX_LEN];
	int this_len = 0;

	for (int i = 0; i < MAX_LEN; i++) {
		num_of_len[i] = 0;
	}

	while ((c = getchar()) != EOF) {
		if ((c == ' ' || c == '\t' || c == '\n') && this_len > 0) {
			if (this_len > MAX_LEN) {
				this_len = MAX_LEN;
			}
			++num_of_len[this_len - 1];
			this_len = 0;
		} else {
			++this_len;
		}
	}

	int highest_count = 0;
	for (int i = 0; i < MAX_LEN; i++) {
		if (num_of_len[i] > highest_count) {
			highest_count = num_of_len[i];
		}
	}
	printf("Highest: %d\n", highest_count);

	for (int row = highest_count; row > 0; row--) {
		for (int col = 0; col < MAX_LEN; col++) {
			putchar(' ');
			if (num_of_len[col] >= row) {
				printf(" #");
			} else {
				printf("  ");
			}
		}
		putchar('\n');
	}

	for (int i = 0; i < MAX_LEN; i++) {
		putchar(' ');
		printf("%2d", i + 1);
	}
	putchar('\n');
}