File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programming Diversions and the fly likes Character Frequency Counter in C(?) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Other » Programming Diversions
Bookmark "Character Frequency Counter in C(?)" Watch "Character Frequency Counter in C(?)" New topic
Author

Character Frequency Counter in C(?)

Caitlin Gibson
Greenhorn

Joined: Nov 25, 2002
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

Joined: Oct 02, 2003
Posts: 11257
    
  16

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 ]

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
Consider Paul's rocket mass heater.
 
subject: Character Frequency Counter in C(?)