6.24
A improve version for the answer book!
Notice:
int isprint ( int c );
Check if character is printable, I first use it to print the x-axis, then I found a extra variable, that’s the blank key, amazing! So, I used the isgraph()returns true for the same cases as isprint except for the whitespace characters (like ' '), which return true when checked with isprint but false when checked with isgraph.
#include <stdio.h>
/* NUM_CHARS should really be CHAR_MAX but K&R haven't covered that at this stage in the book */
#define NUM_CHARS 256
int main(void)
{
int c;
long freqarr[NUM_CHARS + 1];
long thisval = 0;
long maxval = 0;
int thisidx = 0;
for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++)
{
freqarr[thisidx] = 0;
}
while((c = getchar()) != EOF)
{
if(c < NUM_CHARS)
{
thisval = ++freqarr[c];
if(thisval > maxval)
{
maxval = thisval;
}
}
else
{
thisval = ++freqarr[NUM_CHARS];
if(thisval > maxval)
{
maxval = thisval;
}
}
}
for(thisval = maxval; thisval > 0; thisval--)
{
printf("%4d |", thisval);
for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++)
{
if(isgraph(thisidx))
{
if(freqarr[thisidx] >= thisval)
{
printf("*");
}
else if(freqarr[thisidx] > 0)
{
printf(" ");
}
}
}
printf("/n");
}
printf(" +");
for(thisidx = 0; thisidx <= NUM_CHARS; thisidx++)
{
if(freqarr[thisidx] > 0)
{
printf("-");
}
}
printf("/n ");
/*print x-axis */
for(thisidx = 0; thisidx < NUM_CHARS; thisidx++)
{
if(freqarr[thisidx] > 0)
{
if(isgraph(thisidx))
putchar(thisidx);
}
}
printf("/n ");
/*Deal this the extrmely situation*/
if(freqarr[NUM_CHARS] > 0)
{
if(isgraph(NUM_CHARS))
putchar(NUM_CHARS);
printf("/n");
}
printf("/n");
return 0;
}