Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a C Program to count the frequency of each character
In C programming, counting the frequency of each character in a string is a common task that involves scanning through the string and tracking how many times each character appears.
Syntax
int frequency[26]; // For lowercase letters a-z frequency[character - 'a']++; // Increment count for character
Algorithm
Step 1: Define maximum string size Step 2: Declare string and frequency array Step 3: Read input string Step 4: Initialize frequency array to 0 Step 5: Iterate through string and count characters: - For lowercase: frequency[string[i] - 'a']++ - For uppercase: frequency[string[i] - 'A']++ Step 6: Print non-zero frequencies
Example
The following C program counts the frequency of each character in a string −
#include <stdio.h>
#include <string.h>
#define MAX 100
int main() {
char string[MAX];
int i, length;
int frequency[26] = {0}; // Initialize all to 0
/* Input string from user */
printf("Enter the string: ");
fgets(string, sizeof(string), stdin);
length = strlen(string);
/* Count frequency of each character */
for(i = 0; i < length; i++) {
/* Convert to lowercase and count */
if(string[i] >= 'a' && string[i] <= 'z') {
frequency[string[i] - 'a']++;
}
else if(string[i] >= 'A' && string[i] <= 'Z') {
frequency[string[i] - 'A']++;
}
}
/* Print frequency of all characters */
printf("\nCharacter frequencies:
");
for(i = 0; i < 26; i++) {
if(frequency[i] != 0) {
printf("'%c' = %d
", (i + 'a'), frequency[i]);
}
}
return 0;
}
Enter the string: Tutorials Point Character frequencies: 'a' = 1 'i' = 2 'l' = 1 'n' = 1 'o' = 2 'p' = 1 'r' = 1 's' = 1 't' = 3
How It Works
- We use an array of size 26 to store frequencies for letters a-z
- ASCII value manipulation:
'a' - 'a' = 0,'b' - 'a' = 1, etc. - Both uppercase and lowercase letters are mapped to the same index
- Non-alphabetic characters are ignored
Conclusion
Character frequency counting in C uses array indexing based on ASCII values. This approach efficiently handles both uppercase and lowercase letters while ignoring non-alphabetic characters.
Advertisements
