Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Character Frequency Counter in C(?)

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 ]
lowercase baba
Posts: 12871
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 ]
I'm thinking about a new battle cry. Maybe "Not in the face! Not in the face!" Any thoughts tiny ad?
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic