Hello all,
I'm currently working my way through the K&R book and am doing all the exercises as I come across them. This exercise asks me to write a program that prints out a histogram of the number of occurrences of each character in the input. I should note that on the x-axis, I list the ASCII codes of each character that appears in the file because it seemed the most consistent way to display the data while also including whitespace characters.
Here is my code:
Code:
/* Corresponding K&R section: 1.6 */
/* Counts frequencies of different characters in input */
#include <stdio.h>
#define NUM_CHARS 256
int main(void)
{
int c = 0;
int charFrequencies[NUM_CHARS] = {0};
int maxFrequency = 0;
/* -------------- Get Frequency Data --------------- */
while((c = getchar()) != EOF)
charFrequencies[c]++;
/* --------------- Print Histogram ----------------- */
/* NOTE: characters not appearing in the input will not
appear on the x-axis. To allow display of data
for non-printable characters, ASCII codes will
be used on the x-axis. */
//Determine max frequency
for(c = 0; c < NUM_CHARS; c++)
{
if(charFrequencies[c] > maxFrequency)
maxFrequency = charFrequencies[c];
}
//print y-axis and bars
int i = 0;
printf("\n\n");
for(c = maxFrequency; c > 0; c--)
{
printf("%7d | ", c);
for(i = 0; i < NUM_CHARS; i++)
{
if(charFrequencies[i] >= c)
putchar('*');
/* To align with the x-axis, only print
a space if the character appears in
the input */
else if(charFrequencies[i] > 0)
putchar(' ');
}
putchar('\n');
}
//print x-axis
//print dashes
printf(" +-");
for(i = 0; i < NUM_CHARS; i++)
{
if(charFrequencies[i] > 0)
putchar('-');
}
putchar('\n');
//print 100s digit of ASCII code
printf(" ");
for(i = 0; i < NUM_CHARS; i++)
{
if(charFrequencies[i] > 0)
printf("%d", i / 100);
}
putchar('\n');
//print 10s digit of ASCII code
printf(" ");
for(i = 0; i < NUM_CHARS; i++)
{
if(charFrequencies[i] > 0)
printf("%d", (i % 100) / 10);
}
putchar('\n');
//print 1s digit of ASCII code
printf(" ");
for(i = 0; i < NUM_CHARS; i++)
{
if(charFrequencies[i] > 0)
printf("%d", (i % 100) % 10);
}
printf("\n\n");
return 0;
}
I realize I am not using certain library functions that would help condense this code, but part of the challenge of the exercises is to implement a solution using only the components of the C language that I've been exposed to thus far. I'm mainly looking for comment on how well my solution scales with size of input, or if there are any known bad habits I'm indulging in.