Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Problem Statement
2.1.
Approach
2.2.
Implementation
2.3.
Program Explanation
2.4.
Alternate Method
2.5.
Approach
2.6.
Algorithm
3.
Frequently Asked Questions
3.1.
What do you mean by the frequency of characters in a string?
3.2.
What is the most frequent character in a string?
3.3.
What is the least frequent character in a string?
4.
Conclusion
Last Updated: Mar 27, 2024

C Program to find frequency of characters

Author Aditya Singh
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

You'll learn how to find the frequency of a character in a string and obtain the code to do it.

How many times does a specific character appear in a string in that instance?

For example, if the user types in coding ninja and wants to verify the frequency of a particular character, such as n. Then it'll be three because the letter n appears three times in the provided string, coding ninja.

Also see, Binary to Hex Converter,C Static Function

Problem Statement

Write a C program to find the frequency of characters in a given string.

Approach

  1. The string entered by the user is saved in str in this program.
  2. The user is then asked to enter the character whose frequency will be determined. Variable ch is used to hold this information.
  3. The string is then iterated over using a for a loop. The count is incremented by one in each iteration if the character in the string is equal to the ch. Finally, the count variable's frequency is printed.

Implementation

/*  Write a C program to find the frequency of characters in a given string. */
#include <stdio.h>
#include <math.h>
void Solve()
{
    int i, count = 0;
    char str[100], ch;
    printf("Enter the String: ");
    gets(str);
    printf("Enter any character (present in string) to find its frequency: ");
    scanf("%c", &ch);
    for (i = 0; str[i] != '\0'; i++)
    {
         if (ch == str[i])
             count++;
    }
    printf("\nFrequency of %c = %d", ch, count);
    printf("\n\n%c occurs %d times in %s", ch, count, str);
}
int main()
{
    Solve();
    return 0;
}

Time Complexity: O(n), where n is the length of a string. 

Space Complexity: Constant space. 

Output

You can also read about dynamic array in c and  Short int in C Programming

Program Explanation

  1. The gets() function is used to get string input from the user. 
  2. The scanf() function is used to convey character input from the user. 
  3. We've established a for loop to verify every character in the string, starting with the 0th character and ending with the null-terminated character' \0'.
  4. When the character matches the character at any point in the string, the count variable's value is incremented. Because the count variable is initially set to 0, the count represents the total number of times the character appears in the string.

For example, suppose the string is codingninja (in str variable) and the character is n (in ch variable). Therefore, str[0] holds c, str[1] holds o, str[2] holds d, str[3] holds i, ....., str[10] holds j, and str[11] holds a.

The character n presents the index numbers 4, 6, and 8. Total of 3 times. Therefore, the count variable gets incremented three times. As the condition ch==str[i] gets true three times. Because ch holds c and str[4], str[6], and str[8] also holds n. Therefore, the frequency of n in the given string say codingninja will be 3.

Alternate Method

In this method, we are finding the frequency of each character in the string irrespective of user’s input at first. Let’s see the approach for the same: 

Approach

  1. To store the frequency of each alphabet in the given string, create an array freq[]. The frequency of the character 'a' is stored in the 0th index, The frequency of the character 'b' is stored in the 1th index, and so on.
  2. Iterate through the string S, increasing the frequency of each character encountered by 1 for each iteration.
  3. And then after the complete iteration, print the frequency of all the characters in the string.

Algorithm

  1. The string entered by the user is saved in S in this program.
  2. Store the frequency of each alphabet in the given string 
  3. To store the frequency we simple use  freq[S[i] - 'a']++;
  4. Finally, print the frequency of each character in the given string.
/*  Write a C program to find the frequency of characters in a given string. */
#include <stdio.h>
#include <math.h>
#include<string.h>
void frequency(int freq[])
{
    for (int i = 0; i < 26; i++) {
        if (freq[i] != 0) {
            printf("%c = %d Times\n",
                   i + 'a', freq[i]);
        }
    }
}
  
void Solve()
{
    char s[1000];
    int i=0;
    printf("Enter the string: ");
    printf("\n");
    scanf("%s",s);
    int freq[26]={0};
    while (s[i] != '\0') 
    {
        freq[s[i] - 'a']++;
        i++;
    }
    frequency(freq);
}
int main()
{
    Solve();
    return 0;
}

Time Complexity: O(n), where n is the length of the string. 

Space Complexity: O(n), where n is the length of the string. 

Output

You can practice by yourself with the help of online c compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

What do you mean by the frequency of characters in a string?

Freq will be utilized to keep track of the number of characters in the string. Iterate through the string, comparing each character to the rest of it. In freq, increase the count of the appropriate element. Finally, iterate over freq to see the character frequencies.

What is the most frequent character in a string?

The character is repeated most of the time in that particular string or we can say, that character having the maximum frequency in the string is called the most frequent character in the string.

What is the least frequent character in a string?

The character is repeated the least of the time in that particular string or we can say that character having the minimum frequency in the string is called the least frequent character in the string.

Conclusion

In this article, we see the implementation of the C program to calculate the frequency of characters in a string. We had also seen the output of the written program on some random input.

If you want to learn more about C programs, visit the given links below:

Getch in C

Transpose of a Matrix in C.

C Program to count the length of string without using any library function

Bubble Sort Program in C

Armstrong Number in C

Ternary Operator in C

Conditional Operator in C

Program to convert Fahrenheit to Celsius

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Please upvote our blog to help other ninjas grow.

Happy Learning!

Previous article
C Program to check a triangle is a equilateral, isosceles or scalene
Next article
C Program to concatenate two Strings
Live masterclass