You are here:

C++/sorting letters in a frequency analysis


I am writing a program which will do a frequency analysis on a wordlist supplied as an argument to main. I accomplish this by initializing a float for each character I wish to count and incrementing that variable whenever that character is encountered. For example:

float acounter; //counts the number of instances of lowercase letter "a"
acounter = 0;
float totalnumberofcharacters; //total number of characters in list
totalnumberofcharacters = 52,345,545;

for(int i = 0; i<word_list.size();i++) //iterates through every word in wordlist
  for(int c = 0; c<strlen(wordlist[i]);c++) //iterates through every character in word
     if(word[c]=='a') //if current char is "a"
        acounter++; //add one to the "a" counter

std::cout << acounter << " instances of the character "a" (~";
std::cout << (100/ totalnumberofcharacters)*acounter << "%)

and the output is, for example:

C:UsersdzhugashviliDesktop reqanal inal>freqanal wordlist3.txt

5000 instances of the character "a" (~.00955%)

C:UsersdzhugashviliDesktop reqanal inal>

However, I am tired of pasting the percentage occurrence of all 95 characters that are analyzed into notepad and manually rearranging them from order of highest occurrence to least occurrence. Is there any way I could have the program sort them for me? In the best-case scenario, I would get a printout in this format:


just a string of letters from highest occurrence to lowest occurrence. How would I go about this? A 2-D array? Linked lists? Thank you for your help.

Dear Dzhugashvili:

This can be done a number of ways.

One way is to declare a class of char chr and int count.  Then create an array of 100 such structures. Every time you find a character from the list in a word increment the counter.  Once you have counted all the desired characters in the words, sort the array by the counts, then print the characters in order of counts.


All Answers

Answers by Expert:

Ask Experts


Titus B. Ledbetter, Jr.


C , MFC, Object Oriented, Artificial Intelligence


I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Master's Degree Computer Science from Johns Hopkins

©2017 All rights reserved.

[an error occurred while processing this directive]