 # C Programming Code Examples

## C > Strings Code Examples

### C program to count frequency of each character in a string

``` C program to count frequency of each character in a string Write a C program to count frequency of each character in a string using loop. How to find frequency of each characters in a string in C programming. There are many algorithms to count frequency of each character. Here I am explaining the easiest one. Input string from user, store it in some variable say str. To count and store frequency of each alphabet we need an array, say freq. An array of size 26 (since there are 26 alphabets). Each element of the array will hold the occurrence of specific alphabet. For example array will hold the occurrence of a or A alphabet, similarly array will hold frequency of b and so on array will hold frequency of z. Before you begin any processing with the string make sure that freq array elements are initialized to 0. Then for each character ch in the string str repeat next step. If ch == 'a' then increment the value of freq++ by one. Similarly if(ch == 'z') then increment freq++. Now, to make things little easier and to work with every character in the given string we use below logic to increment freq. We use, freq[ch - 97] (For lowercase alphabets) and freq[ch - 65] (For uppercase alphabets) You might think why we have used these values ch - 97 and what it will do? Since, ASCII value of a is 97, b is 98 and so on. Suppose ch = 'c' then we need to increment the value of freq by one. Lets, do a simple mathematics => freq[ ch - 97 ] => freq[ 99 - 97 ] (since ASCII value of c=97) => freq[ 2 ] which works. You can apply the same mathematics with the upper case alphabets i.e. if(ch == 'Z') then we need to perform freq[ ch - 65 ]. #include <stdio.h> #include <string.h> #define maxsize 100 // Maximum string size int main() { char str[maxsize]; int j, len; int freq; /* Input string from user */ printf("Enter any string: "); gets(str); len = strlen(str); /* Initialize frequency of each character to 0 */ for(j=0; j<26; j++) { freq[j] = 0; } /* Find total number of occurrences of each character */ for(j=0; j<len; j++) { /* If the current character is lowercase alphabet */ if(str[j]>='a' && str[j]<='z') { freq[str[j] - 97]++; } else if(str[j]>='A' && str[j]<='Z') { freq[str[j] - 65]++; } } /* Print the frequency of all characters in the string */ printf("\nFrequency of all characters in the given string: \n"); for(j=0; j<26; j++) { /* If current character exists in given string */ if(freq[j] != 0) { printf("'%c' = %d\n", (j + 97), freq[j]); } } return 0; } ```