C Online Compiler
Example: Character Frequency Counter in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Character Frequency Counter #include <stdio.h> #include <string.h> // For strlen() // Define a constant for the number of possible ASCII characters #define ASCII_SIZE 256 int main() { char str[] = "hello world"; int i = 0; // Create an array to store the frequency of each character (our pigeonholes) int freq[ASCII_SIZE] = {0}; // Initialize all counts to 0 printf("Original string: \"%s\"\n", str); // Iterate through the string and increment the count for each character while (str[i] != '\0') { // Use the character's ASCII value as an index (pigeonhole) freq[(unsigned char)str[i]]++; i++; } printf("Character frequencies:\n"); // Print the frequency of characters that appeared for (i = 0; i < ASCII_SIZE; i++) { if (freq[i] > 0) { printf(" '%c' : %d\n", (char)i, freq[i]); } } return 0; }
Output
Clear
ADVERTISEMENTS