C Online Compiler
Example: Character Frequency - Recursive in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Character Frequency - Recursive #include <stdio.h> #define MAX_CHARS 256 // Assuming ASCII characters void calculateFrequencyRecursive(const char *str, int *freq) { // Base case: If the current character is the null terminator, stop recursion if (*str == '\0') { return; } // Recursive step: Increment frequency for the current character // Type casting *str to unsigned char ensures it's treated as a positive index freq[(unsigned char)*str]++; // Call the function for the rest of the string (str + 1) calculateFrequencyRecursive(str + 1, freq); } int main() { char inputString[] = "Hello Recursion!"; int frequency[MAX_CHARS]; // Initialize frequency array to all zeros before the first recursive call for (int i = 0; i < MAX_CHARS; i++) { frequency[i] = 0; } calculateFrequencyRecursive(inputString, frequency); printf("Character frequencies for \"%s\":\n", inputString); for (int i = 0; i < MAX_CHARS; i++) { if (frequency[i] > 0) { printf("Character '%c': %d\n", (char)i, frequency[i]); } } return 0; }
Output
Clear
ADVERTISEMENTS