Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find frequency of a character in a string.

C Code Example — String Programs

ADVERTISEMENT

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

  1. Read a string and read the target character c to search for.
  2. Initialize a count to 0.
  3. Loop through the string character by character.
  4. If the current character matches the target (str[i] == c), increment the count.
  5. 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 a gets() or another scanf, 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)
ADVERTISEMENT