# Program to calculate the Frequency of characters in a string

03 September 2023

Write a Program to calculate the Frequency of characters in a string

## Get 30 minutes free mentorship by TalentBattle Placement Experts If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

## Description about Program to calculate the Frequency of characters in a string

Get a string as the input from the user and find the frequency of characters in the string.

Input

program

Output

The frequency of a is 1

The frequency of g is 1

The frequency of m is 1

The frequency of o is 1

The frequency of p is 1

The frequency of r is 2

## C Program to calculate the Frequency of characters in a string

#include <stdio.h>

#include<string.h>

int main()

{

char str;

int i;

int frequency = {0};

printf("Enter a string: ");

gets(str);

for(i = 0; str[i] != '\0'; i++)

{

frequency[str[i]]++;

}

for(i = 0; i < 256; i++)

{

if(frequency[i] != 0)

{

printf("The frequency of %c is %d\n", i, frequency[i]);

}

}

return 0;

}

## C++ Program to calculate the Frequency of characters in a string

#include <iostream>

#include<string.h>

using namespace std;

int main()

{

char str;

int i;

int frequency = {0};

cout<<"Enter a string: ";

gets(str);

for(i = 0; str[i] != '\0'; i++)

{

frequency[str[i]]++;

}

for(i = 0; i < 256; i++)

{

if(frequency[i] != 0)

{

printf("The frequency of %c is %d\n", i, frequency[i]);

}

}

return 0;

}

## Java Program to calculate the Frequency of characters in a string

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

Scanner sc =new Scanner(System.in);

System.out.print("Enter a string: ");

String str = sc.nextLine();

int[] frequency = new int[str.length()];

int i, j;

char strnew[] = str.toCharArray();

for(i = 0; i <str.length(); i++) {

frequency[i] = 1;

for(j = i+1; j <str.length(); j++) {

if(strnew[i] == strnew[j]) {

frequency[i]++;

strnew[j] = '0';

}

}

}

System.out.println("Frequencies: ");

for(i = 0; i <frequency.length; i++) {

if(strnew[i] != ' ' && strnew[i] != '0')

System.out.println(strnew[i] + " - " + frequency[i]);

}

}

}

## Python Program to calculate the Frequency of characters in a string

Str = input('Enter the string :')

frequency = 0

for i in range(0,len(Str)):

Character = Str[i]

frequency = Str.count(Character)

print(str(frequency) + ' is the frequency of '+Character) 