Advertisement
khalfella

c_ch01_ex14.c

Sep 20th, 2014
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. /*
  2. * Exercise 1-14.
  3. * Write a program to print a histogram of the
  4. * frequencies of different characters in its input.
  5. */
  6.  
  7. #include <stdio.h>
  8.  
  9. #define CHARCOUNT 52
  10. #define HWIDTH 80
  11.  
  12.  
  13. main() {
  14. int c, chrs[CHARCOUNT], i;
  15. int count, max;
  16.  
  17.  
  18. /* initialize the histogram and max */
  19. for (i = 0; i < CHARCOUNT; i++)
  20. chrs[i] = 0;
  21. max = 0;
  22.  
  23. /* populate the histogram */
  24. while ((c = getchar()) != EOF) {
  25. if (c >= 'a' && c <= 'z') {
  26. ++chrs[c - 'a'];
  27. } else if (c >= 'A' && c <= 'Z') {
  28. ++chrs[c - 'A' + 26];
  29. }
  30. }
  31.  
  32. /* calculate max */
  33. for (i = 0; i < CHARCOUNT; i++)
  34. if (chrs[i] > max)
  35. max = chrs[i];
  36.  
  37. /* draw the histogram */
  38. for (i = 0; i < CHARCOUNT; i++) {
  39. if (chrs[i]) {
  40. /* is it a small character */
  41. if (i < 26)
  42. c = i + 'a';
  43. else
  44. c = i - 26 + 'A';
  45.  
  46. printf("[%c] ", c);
  47. for (count = 0; count < (chrs[i]*HWIDTH)/max; count++)
  48. putchar('@');
  49. for (count = 0;
  50. count < HWIDTH - (chrs[i]*HWIDTH)/max; count++)
  51. putchar(' ');
  52. printf(" %6d\n", chrs[i]);
  53. }
  54. }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement