K&R book exercies 1-13 solution and opinions
Hi all! I'm going through K&R by my own and would like some opinions about my solution to this exercise:
"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."
Based on the assumptions that a word is any character different than blank space, tab or new line and that I will receive words of maximum 12 characters long, this is my solution:
#include <stdio.h>
#define MAX_WORD_LEN 12 /* max number of chars per word */
int main(void)
{
int chr;
int i;
int word_length;
int frequencies[MAX_WORD_LEN];
word_length = 0;
while ((chr = getchar()) != EOF) {
if (chr == ' ' || chr == '\t' || chr == '\n') {
if (word_length > 0) {
++frequencies[word_length - 1];
word_length = 0;
}
} else {
++word_length;
}
}
/* print results as a histogram */
for (i = 0; i < MAX_WORD_LEN; ++i) {
printf("%2d|", i + 1);
while (frequencies[i]--)
printf("=");
printf("\n");
}
return 0;
}