C program to count frequency of each character in a string

Category: C Program

Learn how to write a C program to count the frequency of each character in a string. This comprehensive guide includes step-by-step instructions, code implementation, and detailed explanations for beginners in C programming.

In this article, we will explore how to write a C program that counts the frequency of each character in a given string. This task is fundamental in text analysis and processing, where understanding character frequency can be essential for tasks such as data compression, cryptography, and natural language processing.

Objective

The aim is to create a C program that takes a string as input and counts how many times each character appears in the string. The program will then output the frequency of each character.

Approach

To solve this problem, we will:

  1. Read the input string from the user.
  2. Use an array to keep track of the frequency of each character.
  3. Iterate over the string to update the frequency array.
  4. Print the frequency of each character.

Detailed Steps

  1. Read the input string:
    • Use standard input functions to get the string from the user.
  2. Initialize the frequency array:
    • Use an array to count the frequency of each character.
  3. Count character frequencies:
    • Iterate over the string and update the frequency array.
  4. Print the frequencies:
    • Iterate over the frequency array and print the frequency of each character that appears in the string.

Write a C program to count frequency of each character in a string

Below is the complete C program implementing the above steps:

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

#define ASCII_SIZE 256

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

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

    // Remove newline character from string if present
    size_t len = strlen(str);
    if (len > 0 && str[len - 1] == '\n') {
        str[len - 1] = '\0';
    }

    // Count frequency of each character
    for (int i = 0; i < strlen(str); i++) {
        freq[(int)str[i]]++;
    }

    // Print the frequency of each character
    printf("Character frequencies -\n");
    for (int i = 0; i < ASCII_SIZE; i++) {
        if (freq[i] > 0) {
            printf("'%c': %d\n", i, freq[i]);
        }
    }

    return 0;
}

Output

Enter a string: learn programming at ProCoding
Character frequencies -
' ': 3
'C': 1
'P': 1
'a': 3
'd': 1
'e': 1
'g': 3
'i': 2
'l': 1
'm': 2
'n': 3
'o': 3
'p': 1
'r': 4
't': 1

Explanation of the Program

  1. Input Handling:
    • The program uses fgets() to read a line of text from the user, ensuring that spaces and special characters are included.
    • It removes any trailing newline character added by fgets().
    • int freq[ASCII_SIZE] = {0}; this is a shorthand way to initialize every element in the array to 0.
  2. Frequency Array Initialization:
    • An array freq of size 256 (to cover all ASCII characters) is initialized to zero. This array will store the frequency count for each ASCII character.
  3. Frequency Counting:
    • The program iterates over each character in the string and increments the corresponding index in the freq array based on the ASCII value of the character.
  4. Printing Frequencies:
    • The program iterates over the freq array and prints the frequency of each character that appears in the string. Characters with a frequency of zero are skipped.

Recommended Posts