练习1-13
打印出输入单词的直方图
print histogram for words count
用水平方法打印
horizontal
#include <stdio.h>
/* Draw a histogram for words count
with horizontal V1.0 */
#define IN 1
#define OUT 0
int main()
{
int c, i, j, state, nw, nc;
int nlen[46]; //word max is 46.
nw = 0;
for (i = 0; i < 46; ++i)
nlen[i] = 0;
state = OUT;
nc = OUT;
while ((c = getchar()) != EOF){
if (c == ' ' || c == '\t' || c == '\n'){
if (nc > 0)
++nlen[nc];
state = OUT;
nc = OUT;
}
else if (state == OUT){
state = IN;
++nw;
}
if (state == IN && (c != ' ' || c != '\t' || c != '\n'))
++nc;
}
printf("words = %d\n", nw);
for (i = 0; i < 46; ++i){
if (nlen[i] > 0){
if (i < 10)
printf("%d ", i);
else
printf("%d ", i);
for (j = 0; j < nlen[i]; ++j)
printf("#");
printf("%d\n", j);
}
}
}
用垂直方法打印
vertical
#include <stdio.h>
/* This is a program that draw histogram for word count with vertical */
#define IN 1
#define OUT 0
int main()
{
int c, i, nw, nc, state, nmax;
int nlen[18]; //words max 18
nw = nc = nmax = 0;
state = OUT;
for (i = 0; i < 18; ++i)
nlen[i] = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
state = OUT;
if (nc > 0)
++nlen[nc];
nc = OUT;
}
else if (state == OUT) {
++nw;
state = IN;
}
if (state == IN) {
++nc;
}
}
printf("words = %d\n", nw);
for (i = 0; i < 18; ++i)
if (nmax < nlen[i])
nmax = nlen[i];
printf("%d\n", nmax + 2);
printf("%d\n", nmax + 1);
while (nmax >= 0) {
if (nmax >= 10)
printf("%d ", nmax);
else
printf("%d ", nmax);
for (i = 0; i < 18; ++i) {
if (nlen[i] >= nmax)
printf(" ##");
else
printf(" ");
}
printf("\n");
--nmax;
}
printf(" ");
for (i = 0; i < 18; ++i)
printf("%3d", i);
printf("\n");
}