Count frequency of character in string C program

Simple C program to count frequency of each character in a string. If string a "programmingside" then frequency of characters:
 frequency of 'p' = 1;
 frequency of 'r' = 2;
 frequency of 'o' = 1;
 frequency of 'g' = 2;
 frequency of 'a' = 1;
 frequency of 'm' = 2;
 frequency of 'i' = 2;
 frequency of 'n' = 1;
 frequency of 's' = 1;
 frequency of 'd' = 1;
 frequency of 'e' = 1;

To count frequency, declare a character count array and initialize it to 0. Now put string element at the place of subscript in count array and count how many times a character is in string.

C Program:

#include<stdio.h>
#include<string.h>
 
void CountFrequency(char *str)
{
 int i,count[256]={0};
 int n=strlen(str);
 
 for(i=0;str[i];i++)
 {
  count[str[i]]++;
 }
 /* Print character with frequency */
 
 for(i=0;i<n;i++)
 {
  if(count[str[i]]!=0)
  {
  printf("%c = %d\n",str[i],count[str[i]]);
  count[str[i]]=0;
 }
 }
}
 
int main()
{
 char str[100];
 printf("Enter a string: ");
 scanf("%s",str);
 
 CountFrequency(str);
 
 return 0;
}

Another program using pointer

/* stdlib.h library to use malloc, calloc */
#include<stdio.h>
#include<stdlib.h>
#define MAX 256
 
int *CountArray(char *str)
{
 // use calloc to initialize all elements of count array
 // to zero
 int *count=(int *)calloc(sizeof(int),MAX);
 int i=0;
 while(*(str+i)!='\0')
 {
  count[*(str+i)]++;
 }
 return count;
}
 
void CharFrequency(char *str)
{
 int *count=CountArray(str);
 int i;
 for(i=0;*(str+i);i++)
 {
  if(count[*(str+i)]!=0)
  {
   printf("%c = %d\n",*(str+i),count[*(str+i)]);
 // don't want to print string element again so count[*(str+i)]=0
   count[*(str+i)]=0;
  }
 }
}
 
int main()
{
 char str[100];
 printf("Enter a string: ");
    scanf("%s",str);
 CharFrequency(str);
 
 return 0;
}

Popular posts from this blog