]>
zdv2.bktei.com Git - BK-2023-05.git/blob - src/kr_exercises/ch1/s1.6/e1-13..histogram_word_length.c
86184150eb45829f8c9be79f2b05df7ea6d92fc6
3 /* Exercise 1-13. Write a program to print a histogram of the length
4 of words in its input. It is easy to draw the histogram with the
5 bars horizontal; a vertical orientation is more challenging. */
7 #define MAX_LEN 4 /* Max acceptable word length */
8 #define MAX_DISP_LEN 70 /* Max length of horizontal bar */
9 #define IN 1 /* Inside a word */
10 #define OUT 0 /* Outside a word */
13 int n
, c
, i
, j
, state
, nwchar
;
14 int wlen
[ MAX_LEN
+ 1 ];
18 for (int i
= 0; i
<= MAX_LEN
; ++i
)
22 while ( (c
= getchar()) != EOF
) {
23 n
++; /* Track loop number. */
24 /* Check if whitespace */
25 if ( c
== ' ' || c
== '\n' || c
== '\t' ) {
26 /* printf("%d:DEBUG:In whitespace.\n", n); */
27 /* I'm in whitespace */
28 /* Check if I just departed a word */
30 /* Increment appropriate element of wlen[] */
31 if ( nwchar
<= MAX_LEN
)
34 ++wlen
[0]; /* Use zero-index for words longer than MAX_LEN */
36 /* Remember I'm not in a word */
40 /* printf("%d:DEBUG:In word.\n", n); */
42 /* Check if I just departed whitespace*/
44 /* I just started a word. */
51 /* Remember I'm in a word. */
55 /* End of while loop stats */
56 /* printf("%d:DEBUG:nwchar:%d\n", n, nwchar); */
60 /* /\* DEBUG:display wlen[] *\/ */
61 /* printf("wlen[]:"); */
62 /* for (i = 0; i < MAX_LEN; ++i) */
63 /* printf(" %d", wlen[i]); */
68 /* printf("wlen[%d]:%d\n", tn, wlen[tn]); */
71 /* Display wlen[] contents */
72 /* Iterate through elements of wlen[] (skipping zeroth element) */
73 for (i
= 1; i
<= MAX_LEN
; ++i
) {
74 /* Print bar for i'th entry in wlen[] */
76 for (j
= 0; j
< wlen
[i
]; ++j
) {
77 if ( j
< MAX_DISP_LEN
)
84 /* Print bar for 0'th entry in wlen[] (words exceeding MAX_LEN) */
85 printf("%d+: ", MAX_LEN
+ 1 );
86 for (j
= 0; j
< wlen
[0]; ++j
)
87 if ( j
< MAX_DISP_LEN
)
94 /* Author: Steven Baltakatei Sandoval