#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;
}

Recommended Answers

All 2 Replies

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.

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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.