C PROGRAMMING PROGRAM • STRINGS
Count the Frequency of Every Character
Learn how to count the frequency of every character using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
hello
Sample output
e : 1 h : 1 l : 2 o : 1
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
char text[300];
int frequency[256] = {0};
fgets(text, sizeof text, stdin);
for (int index = 0; text[index] != '\0' && text[index] != '\n'; index++)
frequency[(unsigned char) text[index]]++;
for (int value = 0; value < 256; value++)
if (frequency[value] > 0) printf("%c : %d\n", value, frequency[value]);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
e : 1 h : 1 l : 2 o : 1
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Use each unsigned character code as an index into a 256-entry frequency array.
- Display the computed result.
Use each unsigned character code as an index into a 256-entry frequency array.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
