Tuesday, August 16, 2011

Exercise 1-13

Exercise 1-13  Write a program to print a histogram of the lengths of words in its input.

#include <stdio.h>

#define MAXLENGTH 20

void print_histo(unsigned int n)
{
  int j;

  for (j = 0; j < n; ++j)
    putchar('*');

  putchar('\n');
}

int main(void)
{
  int c;
  unsigned int i;
  unsigned int length = 0;

  /* count[0] stores the number of words longer than MAXLENGTH. */

  unsigned int count[MAXLENGTH+1];

  for (i = 0; i <= MAXLENGTH; ++i)
    count[i] = 0;

  do
  {
    switch(c=getchar())
    {
    case ' ':
    case '\t':
    case '\n':
      if (length > 0)
      {
        if (length <= MAXLENGTH)
          count[length]++;
        else
          count[0]++;

        length = 0;
      }
      break;

    default:
      length++;
      break;
    }
  }
  while (c != EOF);

  for (i = 1; i < MAXLENGTH+1; ++i)
  {
    printf("%3d  | ", i);
    print_histo(count[i]);
  }

  printf("%3d+ | ", MAXLENGTH);
    print_histo(count[0]);

  return 0;
}

No comments:

Post a Comment