Program to Find Frequency Of Character in C

Frequency of Character :

Frequency is defined as the number of times it appeared, and here frequency of character is termed as number of times a character appeared in the given string.

Frequency of character

Working of Program :

In the program, we will take a string and a character from the user.

Run
#include<stdio.h>
int main()
{
    
    char str[100] = "prepinsta";
    char ch;
    int count =0;
    
    printf("Enter character you want to find frequency : ");
    scanf("%c", &ch);
    for(int i=0; str[i] != '\0'; i++){
        if(str[i] == ch) count++;
    }
    printf("The frequency of character is %d", count);

    return 0;
}

Output :

Enter character you want to find frequency : e
The frequency of character is 1

In the above program,

  • We take a string of fixed length and user given a character.
  • We run a for loop to traverse the string.
  • In for loop  , we use the if condition to check the first index if find then break the program immediately.
  • If we come out of the loop, then the character is not present in the string .

Example :

Let’s solve same problem, but this time we find first index of the character in the string

Run
#include<stdio.h>
int main() {
    
    char str[100] = "prepinsta";
    char ch;
    
    printf("Enter character you want to find frequency : ");
    scanf("%c", &ch);
    for(int i=0; str[i] != '\0'; i++){
        if(str[i] == ch){
            printf("the first index of character is : %d", i);
            return 0;
        }
    }
    printf("The character is not found in string");

    return 0;
}

Output :

Enter character you want to find frequency : t
the first index of character is : 7

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription