Thursday, 16 March 2017

C Program to find the frequency of the characters of a string

C program to find the frequency of the characters of a string is given below. Approach is simple, we will use an array[] of int (initialized to zero) type which will store the number of occurrence of a character with their ASCII code as index.

For example:

Let 'a' be the character of a string 'ab',  string[0]='a'
ASCII value of 'a' = 97
Now array[string[0]] = array[97] = 1. If we find the a again then value arr[97] will be incremented and same will happen for the other characters of the string.

Program:

#include <stdio.h>
#include <string.h>
int main()
{
    char string[100],result;
    int count[256]={0},i,count1;

    printf("\nEnter the string:  ");
    scanf("%s",string);

    for(i=0;i<strlen(string);i++)
    {
          count[string[i]]++;
    }

    printf("\nThe frequency of characters are: \n");
    for(i=0;i<strlen(string);i++)
    {
          result=string[i];
          printf("\n%c  %d",result,count[string[i]]);
    }
    printf("\n");
    return 0;
}


OUTPUT:


EmoticonEmoticon