C program to count a letter repeated in a sentence.

In C programming, counting the frequency of a specific character in a string is a common task. This program prompts the user to enter a sentence and a character, then counts how many times that character appears in the sentence using strlen() function for string length determination.

Syntax

for(i = 0; i < strlen(string); i++) {
    if(string[i] == character) {
        count++;
    }
}

Algorithm

The logic to count character frequency involves the following steps −

  • Read the input sentence from the user
  • Read the character to be counted
  • Iterate through each character in the string using a loop
  • Compare each character with the target character
  • Increment counter when a match is found
  • Display the final count

Example

Note: This program uses fgets() instead of the deprecated gets() function for secure string input.

Following is the C program to count how many times a letter is repeated in a sentence −

#include <stdio.h>
#include <string.h>

int main() {
    int i, count = 0;
    char c, str[100];
    
    printf("Enter a sentence: ");
    fgets(str, sizeof(str), stdin);
    
    printf("Enter a character to count: ");
    scanf(" %c", &c);
    
    for(i = 0; i < strlen(str); i++) {
        if(str[i] == c) {
            count++;
        }
    }
    
    printf("Letter '%c' appears %d times in the sentence<br>", c, count);
    return 0;
}

Output

Enter a sentence: Programming is fun and challenging
Enter a character to count: g
Letter 'g' appears 3 times in the sentence

Key Points

  • Use fgets() instead of gets() for safer string input
  • The space before %c in scanf(" %c", &c) consumes any leftover whitespace
  • The search is case-sensitive − 'A' and 'a' are treated as different characters
  • Time complexity is O(n) where n is the length of the string

Conclusion

This program effectively demonstrates string traversal and character comparison in C. The combination of strlen() and loop iteration provides a straightforward approach to count character frequency in any given text.

Updated on: 2026-03-15T13:55:45+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements