Wednesday, August 17, 2011

Exercise 1-14

Exercise 1-14  Write a program to print a histogram of the frequencies of different characters in its input.

#include <ctype.h>
#include <limits.h>
#include <stdio.h>

#define MAX_WIDTH 65
#define RANGE CHAR_MAX-CHAR_MIN+1

int main(void)
{
  int c;
  unsigned int i;
  unsigned int count[RANGE];

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

  while (c=getchar(), c!=EOF)
  {
    if (count[c-CHAR_MIN]<MAX_WIDTH)
      count[c-CHAR_MIN]++;
  }

  for (i = 0; i < RANGE; i++)
  {
    if (count[i])
    {
      if (isprint(i+CHAR_MIN))
        printf ("%4d '%c' : ", i+CHAR_MIN, i+CHAR_MIN);
      else
        printf ("%4d     : ", i+CHAR_MIN);

      do
      {
        putchar('*');
        count[i]--;
      }
      while(count[i]);

      putchar('\n');
    }
  }

  return 0;
}

No comments:

Post a Comment