0
0
CProgramBeginner · 2 min read

C Program to Find Frequency of Character in String

To find the frequency of a character in a string in C, use a loop to check each character and count matches with if (str[i] == ch) count++;.
📋

Examples

Inputstring = "hello", character = 'l'
OutputFrequency of 'l' = 2
Inputstring = "programming", character = 'm'
OutputFrequency of 'm' = 2
Inputstring = "abc", character = 'z'
OutputFrequency of 'z' = 0
🧠

How to Think About It

To find how many times a character appears in a string, look at each letter one by one. Compare it with the character you want to count. If they are the same, add one to your count. Keep doing this until you reach the end of the string.
📐

Algorithm

1
Get the input string and the character to find.
2
Set a counter to zero.
3
Go through each character in the string one by one.
4
If the current character matches the target character, increase the counter by one.
5
After checking all characters, return or print the counter value.
💻

Code

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

int main() {
    char str[100], ch;
    int count = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    printf("Enter a character to find frequency: ");
    scanf(" %c", &ch);

    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == ch) {
            count++;
        }
    }

    printf("Frequency of '%c' = %d\n", ch, count);
    return 0;
}
🔍

Dry Run

Let's trace the input string "hello" and character 'l' through the code.

1

Input

string = "hello", character = 'l', count = 0

2

Check each character

i=0: 'h' != 'l', count=0 i=1: 'e' != 'l', count=0 i=2: 'l' == 'l', count=1 i=3: 'l' == 'l', count=2 i=4: 'o' != 'l', count=2

3

End of string

Loop ends at i=5 (null character), final count=2

IndexCharacterMatch with 'l'?Count
0hNo0
1eNo0
2lYes1
3lYes2
4oNo2
💡

Why This Works

Step 1: Reading input

The program reads the string and the character to find from the user using fgets and scanf. It removes the trailing newline character from the input string.

Step 2: Looping through string

It uses a for loop to check each character until it finds the end marked by \0.

Step 3: Counting matches

Inside the loop, it compares each character with the target using if (str[i] == ch) and increases the count if they match.

Step 4: Displaying result

After the loop, it prints the total count of how many times the character appeared.

🔄

Alternative Approaches

Using while loop
c
#include <stdio.h>
#include <string.h>

int main() {
    char str[100], ch;
    int count = 0, i = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    printf("Enter a character to find frequency: ");
    scanf(" %c", &ch);

    while (str[i] != '\0') {
        if (str[i] == ch) {
            count++;
        }
        i++;
    }

    printf("Frequency of '%c' = %d\n", ch, count);
    return 0;
}
This uses a while loop instead of for loop; functionally similar but shows a different looping style.
Using array to count all characters
c
#include <stdio.h>

int main() {
    char str[100];
    int freq[256] = {0};

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    for (int i = 0; str[i] != '\0'; i++) {
        freq[(unsigned char)str[i]]++;
    }

    printf("Character frequencies:\n");
    for (int i = 0; i < 256; i++) {
        if (freq[i] > 0 && i != '\n') {
            printf("'%c' = %d\n", i, freq[i]);
        }
    }
    return 0;
}
This counts frequency of all characters at once using an array; useful if you want all counts, but uses more memory.

Complexity: O(n) time, O(1) space

Time Complexity

The program checks each character once, so time grows linearly with string length.

Space Complexity

Only a few variables are used, so space is constant regardless of input size.

Which Approach is Fastest?

Counting frequency of a single character with a loop is fastest and simplest; using an array for all characters uses more space but can be faster if many queries are needed.

ApproachTimeSpaceBest For
Single character loopO(n)O(1)Counting one character frequency
While loopO(n)O(1)Same as for loop, different style
Array frequency countO(n)O(256)Counting all characters at once
💡
Remember to handle newline characters when reading strings with fgets to avoid counting them.
⚠️
Beginners often forget to include a space before %c in scanf, causing input issues.