Guest User

Untitled

a guest
Oct 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. /* *
  4. * Exercise 1-13. Write a program to print a histogram of the lengths of words in
  5. * its input. It is easy to draw the histogram with the bars horizontal; a vertical
  6. * orientation is more challenging.
  7. * ----
  8. * ANSI C K&R - CHARACTER INPUT AND OUTPUT: PAGE 15
  9. * The quantities IS_LOWER, IS_UPPER, IS_ALPHA, MAXLEN, OUT and IN (macros)
  10. * are symbolic constant, not variables, so they do not appear in declarations.
  11. * Symbolic constant names are conventionally written in upper case so they can
  12. * be readily distinguished from lower case variable name.
  13. * */
  14. #define IS_UPPER(N) ((N) >= 'A' && (N) <= 'Z') /* 'A' == 65 && 'Z' == 90 */
  15. #define IS_LOWER(N) ((N) >= 'a' && (N) <= 'z') /* 'a' == 97 && 'z' == 122 */
  16. #define IS_ALPHA(N) (IS_LOWER(N) || IS_UPPER(N)) /* matches: [A-Za-z] */
  17. #define MAXLEN 11 /* buffer limit length */
  18. #define OUT 0 /* outside the word */
  19. #define IN 1 /* inside the word */
  20.  
  21. int main(void)
  22. {
  23. int c = EOF,
  24. /* word buffer & word length */
  25. wbuf[MAXLEN],
  26. wlen = 0;
  27. int state = OUT,
  28. /* X and Y axis */
  29. x = 0, /* horizontal histogram */
  30. y = 0; /* vertical histogram */
  31.  
  32. /* fill word buffer with zero */
  33. for (int i = 0; i <= MAXLEN; i++)
  34. wbuf[i] = 0;
  35.  
  36. /* word count while giving data */
  37. while((c = getchar()) != EOF) {
  38. if (IS_ALPHA(c) && wlen < MAXLEN) {
  39. state = IN;
  40. ++wlen;
  41. } else if (wlen > 0 && wlen < MAXLEN) {
  42. state = OUT;
  43. ++wbuf[wlen];
  44. wlen = 0;
  45. }
  46. }
  47. ++wbuf[wlen]; /* return value without EOF */
  48.  
  49.  
  50. /* give to 'x' and 'y' the length of longest word */
  51. for (int i = 1; i < MAXLEN; i++) {
  52. if (i > x)
  53. x = i;
  54. if (wbuf[i] > y)
  55. y = wbuf[i];
  56. }
  57.  
  58. /* horizontal histogram */
  59. puts("\nHORIZONTAL HISTOGRAM");
  60. for (int i = 1; i <= x; i++) {
  61. printf("%2d |", i);
  62. for (int j = 0; j < wbuf[i]; j++)
  63. putchar('*');
  64.  
  65. putchar('\n');
  66. }
  67.  
  68.  
  69. /* *
  70. * vertical histogram
  71. * building the 'y' axis
  72. * */
  73. puts("\nVERTICAL HISTOGRAM");
  74. for (int i = y; i > 0; i--) {
  75. printf("%2d|", y);
  76. for(int j = 1; j <= x; j++) {
  77. if (i > wbuf[j])
  78. printf(" ");
  79. else
  80. printf("* ");
  81. }
  82. putchar('\n');
  83. }
  84. printf(" +");
  85. for (int i = 1; i <= x; i++)
  86. printf("----");
  87. putchar('\n');
  88.  
  89. for (int i = 1; i <= x; i++)
  90. printf("%4d", i);
  91. putchar('\n');
  92.  
  93. return 0;
  94. }
Add Comment
Please, Sign In to add comment