Letter frequency counter C program – Using Bucket

letter frequency counter C program –  Bucketing mechanism will be used to count frequency of each letters or any characters in a string. also, it can handle any type of characters in the given string.

For example, if the string is : “ABBCDAACCC” then below is the output print

A = 3
B = 2
C = 4
D = 1

Logic is simple –

Step-1: Create an extra bucket (int array) of size 256 (count of ASCII of chars) and initialize with 0 value. Bucket index will represent the ascii value of input characters or letters.

Step-2Traverse the string and convert each char to its ascii value. now, ascii value is the index for bucket. go the bucket[index] and increment the value by 1. If another same character comes the index will be same and again value at that index will be increased from 1 to 2 and so on.

Step -3: Traverse the entire bucket and print its chars and value from bucket.

C program to find the occurrence of a character in a string


/*--------------------------------------------------
* C program to find the occurrence of a 
character in a string
* This program will handle letters and
* all characters
*/

#include<stdio.h>
//Recieve array and print it.
void CharsFrequency(char *arr, int len) {  
	int i =0;
	int bucketLen =0;
	
	//Create a temp bucket to store counter 
	//with the size of 256. 
	//Initialize all 256 slots of the
	//bucket with 0
	int bucket[256] = {0} ;

	//Traverse input char array
	for( i; i<len;++i)
	{
		char c = arr[i];
		//convert char to ANSCII number go get
		//index for bucket array.
		int a =(int)c;
		//increament the value of
		//bucket at index a
		bucket[a] = bucket[a]+1;		
	}  
	
	//Traverse the bucket and print 
	//chars and its count
	bucketLen = sizeof(bucket)/sizeof(bucket[0]); 

	for( i =0; i<bucketLen; ++i)
	{
		if(bucket[i] != 0)
		printf("\n%c = %d",(char)i,bucket[i]);
	}  
 }

int main(){
	
	char cArray[] = "ooooo!!!!&&&";

	//Calculate the lenght of array using
	//sizeof operator or in built strlen() function.	
	//int len = sizeof(cArray)/sizeof(cArray[0]); 
	//or
	int len = strlen(cArray);	
		
	CharsFrequency(cArray, len);
	
	 
	return 0;
}

Related Posts