C Program to find frequency of a character in a string.
Objective
Write a C program to find the frequency (occurrence) of a specific character in a string.
Algorithm / Approach
- Read a string and read the target character
cto search for. - Initialize a
countto 0. - Loop through the string character by character.
- If the current character matches the target (
str[i] == c), increment the count. - Print the total count.
main.c
#include<stdio.h>
int main() {
char str[40],c;
int i,count=0;
printf("Enter a String :");
gets(str);
printf("Enter a character :");
scanf("%c",&c);
for(i=0 ; str[i] !='\0' ;i++) {
if(str[i]==c) {
count++;
}
}
printf("%d time(s).",count);
return 0;
}
Expected Output
Enter a String : C PROWESS APP Enter a character : P 3 time(s).
Explanation of the Program
- This is a simple linear traversal algorithm.
- Note: When using
scanf("%c", &c)immediately after agets()or anotherscanf, there is often a hidden newline character left in the input buffer that gets accidentally consumed by the `%c`. In professional code, it is common to put a space before `%c` (e.g.,scanf(" %c", &c)) to force it to ignore whitespace.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)