Program to find frequency of occurrence of a character

Description

To find frequency of a character in a string take a loop from start
to end and check how many times a given character present. In this
program, user will provide a string and a character as input and 
program give total number of occurrence of that character.

C/C++

/* C Program to find frequency of occurrence of a character*/
//Save it as FrequencyCharacters.c

#include<stdio.h>
int main(){

    char str[50], charVal;
    int i, count=0;

    printf("Enter a string : ");
    scanf("%s",str);
    fflush(stdin);

    printf("Enter the character for which frequency need to find : ");
    scanf("%c",&charVal);

    for(i=0;i<strlen(str);i++){
        if(str[i] == charVal){
            count++;
        }
    }

    printf("The total %c in %s is %d",charVal,str,count);

    return 0;
}
Input:
Enter a string : meera
Enter the character for which frequency need to find : e

Output:
The total e in meera is 2

Java

/* Java Program to find frequency of occurence of a character*/
//Save it as FrequencyCharacters.java

import java.io.*;
import java.util.Scanner;

public class FrequencyCharacters {

    public static void main(String[] args) {
        
            Scanner scanner = new Scanner(System.in);
        
            String str; 
            char charVal;
        int i, count=0;

        System.out.println("Enter a string : ");
        str = scanner.nextLine();

        System.out.println("Enter the character for which frequency need to find : ");
        charVal = scanner.next().charAt(0);

        for(i=0;i<str.length();i++){
            if(str.charAt(i) == charVal){
                count++;
            }
        }

        System.out.println("The total "+charVal+" in "+str+" is "+count);
    }
}
Input:
Enter a string : 
meera
Enter the character for which frequency need to find : 
e

Output:
The total e in meera is 2

Related programs

1) Program to find largest and smallest character in a String
2) Program to Find ASCII value of a character
3) Program to Check Whether a Character is a Vowel or Not
4) Program to sort characters of strings in alphabetical order
5) Program to check entered character is vowel or consonants
6) Program to count uppercase and lowercase alphabet characters in String
7) Count Number of Words in a String
8) Program to remove given number from a string
9) Program to Sort set of strings in alphabetical order
10) Program to Reverse a String
Share Me

Leave a Reply