Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Character Frequency Counter in C(?)

Caitlin Gibson
Greenhorn
Posts: 12
Hi.

I'm currently teaching myself 'C' with 'Teach Yourself C in 21 Days' and I'm using an old edition I've had for years. In chapter 14, an exercise says: Using redirection, i.e., 'prog_name.c < input_file', write a character frequency counter. One hint is provided: Create an array of 26 integers and increment the appropriate array index.

My code thus far is:

I'm considering utilizing a 'for' loop to increment the array indexes and to display the frequency values, e.g., a=2, b=19, etc.

Any help would be most appreciated.

Thanks,

Caitlin
[ June 30, 2008: Message edited by: Caitlin Gibson ]

fred rosenberger
lowercase baba
Bartender
Posts: 12126
30
i'd do it a little simpler... with your method, for each character read, you have to do on average 13 comparisons before you find the spot to increment. also, you seem to be using the same array to store both the value of the caracter (i.e. 'a' = 96) and the count of how many letter of that type. I think this will give you very confusing results.

what' i'd probably do is declare my array to be bigger:

int letters[123] = {0};

the use the ascii value of the letter as your index into the array. so, you'd read a character, and then increment the int at that index

while (!EOF)
ch = getch();
int[ch]++;

then, when your done, iterate over the array starting at 97 and going to 122. you can print the index as a char, and the value at that index is the count.

sure, you waste a little memory with the extra 97 ints you never use, but you save a lot of computations. if memory is an issue (i.e. it's a mobile device with severe memory limitations (which i doubt), you can declare the array to be 26 in size, then use "ch - 'a'" as your index.

note that this may not work if you aren't using an ascii character set...
[ July 01, 2008: Message edited by: fred rosenberger ]