exc/k&r/01-a-tutorial-introduction/01-13.c

68 lines
1.5 KiB
C

#include <stdio.h>
#define MAXLEN 10
/* print historgram of word lengths */
void main()
{
int c, i, len;
/* no word has len = 0; we subscribe with count-1 */
/* the last element is the count of words wiht len > MAXLEN */
int counts[MAXLEN + 1];
/* initializing */
len = 0;
for (i = 0; i <= MAXLEN; ++i)
counts[i] = 0;
/* counting */
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
if (len > 0) {
if (len > MAXLEN)
++counts[MAXLEN];
else
++counts[len-1];
len = 0;
}
continue;
}
++len;
}
int j, max, bound;
bound = max = 0;
for (i = 0; i <= MAXLEN; ++i)
if (counts[i] > 0) {
bound = i;
if (counts[i] > max)
max = counts[i];
}
/* printing horizontal */
printf("----- horizontal -----\n");
for (i = 0; i <= bound; ++i) {
if (i == MAXLEN)
printf(">%2d ", MAXLEN);
else
printf("%3d ", i + 1);
for (j = 0; j < counts[i]; ++j)
putchar('#');
putchar('\n');
}
printf("\n\n");
/* printing vertical */
printf("----- vertical -----\n");
for (i = max; i > 0; --i) {
for (j = 0; j <= bound; ++j)
if (counts[j] >= i)
putchar('#');
else
putchar(' ');
putchar('\n');
}
}