C PROGRAMMING PROGRAM • STRINGS
Count the Frequency of a Character in a String
Learn how to count the frequency of a character in a string using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
banana a
Sample output
'a' occurs 3 time(s)
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
char text[300], target;
int count = 0;
fgets(text, sizeof text, stdin);
printf("Enter character to count: ");
scanf("%c", &target);
for (int index = 0; text[index] != '\0'; index++)
if (text[index] == target) count++;
printf("'%c' occurs %d time(s)\n", target, count);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
'a' occurs 3 time(s)
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Compare every string character with the target and increment on equality.
- Display the computed result.
Compare every string character with the target and increment on equality.
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.
