c
  1. c-program-to-find-the-frequency-of-characters-in-a-string

Program to Find the Frequency of Characters in a String - (C Programs)

In this tutorial, we will learn how to write a C program to find the frequency of characters in a string. We will use loops and arrays to perform this task.

Syntax

The syntax for finding the frequency of characters in a string using C program is as follows:

#include<stdio.h>
#include<string.h>
int main()
{
    char str[1000], ch;
    int i, frequency = 0;

    printf("Enter a string: ");
    gets(str); //Read string input from user

    printf("Enter a character to find the frequency: ");
    scanf("%c", &ch); //Read the character whose frequency is to be found

    for(i = 0; i < strlen(str); i++) //Loop through each character in the string
    {
        if(ch == str[i])
        {
            frequency++;
        }
    }

    printf("The frequency of %c is %d", ch, frequency);

    return 0;
}

Example

Suppose we have a string "Hello, World!". We want to find the frequency of the character "l" in the string. The C program to perform this task would be:

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

int main()
{
    char str[] = "Hello, World!";
    char ch = 'l';
    int frequency = 0;

    for(int i = 0; i < strlen(str); i++)
    {
        if(ch == str[i])
        {
            frequency++;
        }
    }

    printf("The frequency of %c is %d", ch, frequency);

    return 0;
}

Output

The output of the above program will be:

The frequency of l is 3

Explanation

In this program, we declare a string variable "str" and a character variable "ch". We use a for loop to iterate through each character in the string and check if it is equal to the character "ch". If it is, then we increment the frequency by 1. Finally, we print the frequency of the character.

Use

This C program finds the frequency of characters in a string. It can be used as a utility to analyze text data and understand the distribution of characters in a given text string.

Summary

In this tutorial, we learned how to write a C program to find the frequency of characters in a string. We used loops and arrays to perform this task and learned the syntax, example, output, explanation, use and summary of the program. By using this program, we can quickly analyze text data and identify the frequency of specific characters in a given string.

Published on: