Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Character Frequency Counter in C(?)  RSS feed

Caitlin Gibson
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.


[ June 30, 2008: Message edited by: Caitlin Gibson ]
fred rosenberger
lowercase baba
Posts: 12527
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();

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 ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!