0
#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']++;  /*I do not understand this line/*
      c++;
   }
   for (c = 0; c < 26; c++)
   {

      if (count[c] != 0)
         printf("%c  %d \n",c+'a',count[c]);
   }
   return 0;
}
3
Contributors
2
Replies
21
Views
1 Year
Discussion Span
Last Post by David W
1

Hi Mir Mahfuz welcome to Daniweb! :)
What the line does is mapping every character of your string to an index in the your count array.
Say string[c] = 'b' so ('b' - 'a') will be 1 and count[1] will be incremented.
Say string[c] = 'a' so ('a' - 'a') will be 0 and count[0] will be incremented.
etc. etc.

0

count frequency

Your title might have given you an hint about what was happening ...

Your goal seems to have been to find the frequency of each lower case letter in some input string ... lower case letters in the range 'a' to 'z'

Note also the 'hint' further provided to you here:

for (c = 0; c < 26; c++) /* Note mapping 0..25 to 'a'..'z' below */
{
    if (count[c] != 0) /* ONLY print letters with non-zero frequencies */
        printf("%c  %d \n", c+'a', count[c]);  /* print letter frequency */
}

Note also ... the well known dangers of buffer overflow using gets ... so much safer instead to use fgets

@Mir Mahfuz, we do hope you will put to good use and pass on your knowledge gained as you 'frequent' DANIWEB :)

Edited by David W

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.