Sunday , 23 April 2017
Home » ICSE Important Programs » Program to find frequency of every digit in a number

Program to find frequency of every digit in a number

Question:

Write a program to input a number. Count and print the frequency of each digit present in that number. The output should be given as:
Sample Input: 44514621
Sample Output:
=====================
Digit             Frequency
=====================
1                         2
2                         1
4                         3
5                         1
6                         1

Programming Code:

/**
* The class Digit_Freq inputs a number and counts the frequency of each digit present in it
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.io.*;
class Digit_Freq
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter any number : ");
        int n = Integer.parseInt(br.readLine());

        int freq[]=new int[10]; //array for storing frequency of all digits

        for(int i=0; i<10; i++)
            {
                freq[i]=0; //intializing the count of every digit with '0'
            }

        /*Note: Frequency of digit '0' is stored in freq[0], frequency of '1' in freq[1] and so on*/

        System.out.println("Output:");
        System.out.println("===================="); //this is just for styling the look of the output
        System.out.println("Digit\tFrequency");
        System.out.println("====================");

        int d;
        while(n>0)
        {
            d=n%10; //extracting digit from the end
            freq[d]++; //increasing the frequency of that digit.
            n=n/10;
        }
            
        for(int i=0; i<10; i++)
            {
                if(freq[i]!=0) //printing only those digits whose count is not '0'
                    System.out.println("   "+i+"\t    "+freq[i]);
            }
        }
    }

Output:

Enter any number : 937825770

Output:
=====================
Digit             Frequency
=====================
0                          1
2                          1
3                          1
5                          1
7                          3
8                          1
9                          1

Check Also

[Question 1] ISC 2017 Computer Practical Paper Solved – Box Packing

Solution of Program 1 of ISC 2017 Computer Science Paper 2 (Practical) Exam. Java program to input number of boxes to be packed and display the break-up of the cartons used in descending order of capacity

5 comments

  1. Thank you for publishing this program:-)

  2. Can this program be done without using array??

  3. WAP to accept a number and check whether the no. is duck or not. A duck no. contains digit 0.

Leave a Reply to Java For School Cancel reply

Your email address will not be published. Required fields are marked *