Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Find the Frequency of Characters in a String


Write a C program that counts the frequency of each character in a given string:

  • Reads the input string character-by-character until a newline (\n) is encountered.
  • Terminates the string with a null character (\0) after input is complete.
  • Takes a character input (with leading space in scanf to ignore leftover newline).
  • Traverses the string and increments a counter each time the character matches the input.
Example : pgm.c
#include <stdio.h>

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

    printf("Enter a string: ");
    while ((str[i] = getchar()) != '\n') {
        i++;
    }
    str[i] = '\0';

    printf("Enter the character to count: ");
    scanf(" %c", &ch);  // Notice the space before %c to consume newline

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

    printf("The character '%c' appears %d time(s) in the string.\n", ch, count);

    return 0;
}

Output :

Enter a string: Welcome
Enter the character to count: e
The character 'e' appears 2 time(s) in the string.