Advertisement
khalfella

c_ch01_ex13.c

Sep 20th, 2014
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. /*
  2. * Exercise 1-13.
  3. * Write a program to print a histogram of the lengths of words in its input.
  4. * It is easy to draw the histogram with the bars horizontal; a vertical
  5. * orientation is more challenging.
  6. */
  7.  
  8. #include <stdio.h>
  9. #define IN 1 /* inside a word */
  10. #define OUT 0 /* outside a word */
  11. #define MAXLEN 64
  12. #define HWIDTH 80
  13.  
  14. /* count lines, words, and characters in input */
  15.  
  16. main() {
  17. int c, state, i;
  18. int wlen[MAXLEN], len, max;
  19.  
  20.  
  21. state = OUT;
  22. len = 0;
  23. for (i = 0; i < MAXLEN; i++)
  24. wlen[i] = 0;
  25. max = 0;
  26.  
  27. while ((c = getchar()) != EOF) {
  28. if (c == ' ' || c == '\n' || c == '\t') {
  29. if (state == IN) {
  30. state = OUT;
  31. /* we need to consider this word */
  32. if (len < MAXLEN) {
  33. ++wlen[len];
  34. }
  35. len = 0;
  36. }
  37. } else {
  38. state = IN;
  39. ++len;
  40. }
  41. }
  42.  
  43. for (i = 0; i < MAXLEN; i++)
  44. if (wlen[i] > max)
  45. max = wlen[i];
  46.  
  47. for (i = 0; i < MAXLEN; i++) {
  48. if (wlen[i]) {
  49. printf("%2d ", i);
  50. for (len = 0; len < (wlen[i]*HWIDTH)/max; len++)
  51. putchar('@');
  52. for (len = 0;
  53. len < HWIDTH - (wlen[i]*HWIDTH)/max; len++)
  54. putchar(' ');
  55. printf(" %6d\n", wlen[i]);
  56. }
  57. }
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement