K&R Solutions - 1.13, Part 1

Q: 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.

A:

#include <stdio.h>

int main(void) 
{
  /* Because of screen space and the limitations of terminal output, words
   * longer than ten are going to be categorized as greater than 10.
   * 
   * In this model, frequencies[0] is a one-character word, and frequencies[1]
   * is a two-character word. This 'off-by-one' behaviour seems unintuitive
   * and certainly leads to bugs, but there is a very good, low-level reason
   * that becomes very obvious when you learn a bit of assembly. You could find
   * a work-around (like leaving frequencies[0] unused), but it's better to get
   * use to thinking of things as starting with the 0th element because, in the
   * long run, there's no real avoiding it in programming.
   */
  int FREQUENCY_LENGTH = 10; 
  // It's tradition to capitalize this we won't be changing.
  int frequencies[FREQUENCY_LENGTH];
  int i, j, c;
  int tally = 0;

  /* Initialize all frequencies to 0 */
  /* The book hasn't told us this yet, but the easiest way to initiate all
   * elements in an array to 0 is simply to go:
   * int frequencies[10] = {0};
   * BUT doing it with what the book has tought us gives us a better feel for
   * the way that arrays work.
   */
  for (i = 0; i < FREQUENCY_LENGTH; ++i) {
    frequencies[i] = 0;
  }

  /* Count word-length frequencies */
  /* I'm missing colons and semi-colons here for the sake of space, but you get
   * the drift. In a professional setting, you would probably want to create 
   * a separate subroutine called is_word_barrier() to keep your code cleaner
   * and more readable, but we haven't got to that part of the book yet. 
   */
  while ((c = getchar()) != EOF) {
    if (c == '.' || c == '\n' || c == '\t' || c == ' ' || c == ',') {
      if (tally > FREQUENCY_LENGTH) {
        tally = FREQUENCY_LENGTH - 1;
      }
      ++frequencies[tally];
      tally = 0;
    } else {
      ++tally;
    }
  }

  /* Print horizontal-barred histogram */
  printf("\n");
  printf("Word Frequencies: Horizontal\n");
  printf("----------------------------\n");
  for (i = 0; i < FREQUENCY_LENGTH; ++i) {
    if (i != 0) {
      if (i == FREQUENCY_LENGTH - 1) {
        printf("%3d+ | ", i);
      } else {
        printf("%3d  | ", i);
      } 
      for (j = 0; j < frequencies[i]; ++j) {
        printf("-");
      }
      printf("\n");
    }
  }

  return 0;
}
The worst of misery
Is when a nature framed for noblest things
Condemns itself in youth to petty joys,
And, sore athirst for air, breathes scanty life
Gasping from out the shallows.
Supercalifragilisticexpialidocious.

(ctrl+d)

Word Frequencies: Horizontal
----------------------------
  1  | -
  2  | ----
  3  | -------
  4  | -----
  5  | ---
  6  | ------
  7  | ---
  8  | ---
  9+ | -