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

27 June 2022

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


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

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

#include <stdio.h>

#include<string.h>

int main()

{

    char str[100];

    int i;

    int frequency[256] = {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

#include <iostream>

#include<string.h>

using namespace std;

int main()

{

    char str[100];

    int i;

    int frequency[256] = {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

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

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)

 

Related Articles

Ask Us Anything !