C Online Compiler
Example: Character Frequency - Iterative with Pointers in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Character Frequency - Iterative with Pointers #include <stdio.h> #include <string.h> // Required for strlen #define MAX_CHARS 256 // Assuming ASCII characters void calculateFrequencyIterative(const char *str, int *freq) { // Initialize frequency array to all zeros for (int i = 0; i < MAX_CHARS; i++) { freq[i] = 0; } // Iterate through the string using a pointer const char *ptr = str; while (*ptr != '\0') { // Increment frequency for the character pointed to by ptr // Type casting *ptr to unsigned char ensures it's treated as a positive index freq[(unsigned char)*ptr]++; ptr++; // Move the pointer to the next character } } int main() { char inputString[] = "Programming is fun."; int frequency[MAX_CHARS]; calculateFrequencyIterative(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