-
Notifications
You must be signed in to change notification settings - Fork 0
/
histogram.c
48 lines (41 loc) · 927 Bytes
/
histogram.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* write a program to print a histogram of the lengths of words in its input*/
#include <stdio.h>
#define MAXWORDLEN 10
#define IN 1
#define OUT 0
main() {
int c, wordlen, state;
int word[MAXWORDLEN + 1];
wordlen = 0;
state = OUT;
// fill array with zeros
for (int i = 0; i < MAXWORDLEN + 1; i++) {
word[i] = 0;
}
while ((c = getchar()) != EOF) {
if (c == '\n' || c == ' ' || c == '\t') {
state = OUT;
++word[wordlen];
wordlen = 0;
}
else if (state == OUT) {
state = IN;
++wordlen;
}
else {
++wordlen;
}
// for (int i = 0; i <= MAXWORDLEN + 1; ++i) {
// printf("%d: ", i);
// for (int n = 0; n <= word[i]; ++n) {
// printf("-");
// }
// printf("\n");
// }
}
printf("Word length\tCount\n");
for (int i = 1; i < MAXWORDLEN + 1; i++) {
printf("%6d\t\t%d\n", i, word[i]);
}
printf("\n");
}