Search code examples
cpercentagefrequencyletter

How to change letter frequency to percentage?


#include <stdio.h>
#include <string.h>

int main()
{
   char string[100];
   int c = 0, count[26] = {0};

   printf("Enter a string\n");
   gets(string);

   while ( string[c] != '\0' )
   {

      if ( string[c] >= 'a' && string[c] <= 'z' ) 
         count[string[c]-'a']++;

      else if (string[c] >= 'A' && string[c] <= 'Z')
         count[string[c]-'A']++;
      c++;

   }

   for ( c = 0 ; c < 26 ; c++ )
   {
      if( count[c] != 0 )
     printf( "%c %d\n", c+'a', count[c]);
   }

   return 0;
}

So I managed to get the code working to count the letter frequencies as a number. But my assignment tells me to represent it as a percentage of the whole string.

So for example, the input aaab would give me a - 0.7500, b - 0.2500.

How would I modify this code to represent it as a percentage rather than a number?

Also, if I were to do this where the user inputs strings until EOF, do I just delete the "Enter a string" print statement and change while ( string[c] != '\0' ) to while ( string[c] != EOF )?


Solution

  • Just add an accumulative variable that each time that it reads a character, it is incremented by one (assuming that you want to count frequency among valid characters a-z and A-Z). In the end, divide the count by such variable.

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
       char string[100];
       int c = 0, count[26] = {0};
       int accum = 0;
    
       printf("Enter a string\n");
       gets(string);
    
       while ( string[c] != '\0' )
       {
    
          if ( string[c] >= 'a' && string[c] <= 'z' ){
             count[string[c]-'a']++;
             accum++;
          }
    
          else if (string[c] >= 'A' && string[c] <= 'Z'){
              count[string[c]-'A']++;
              accum++;
          }
          c++;
       }
    
       for ( c = 0 ; c < 26 ; c++ )
       {
          if( count[c] != 0 )
              printf( "%c %f\n", c+'a', ((double)count[c])/accum);
       }
    
       return 0;
    }