Java Program to find frequency of every digit in a number


Introduction


This program helps to retrieve Frequency of the digits from provided number. Like number 52458 is having below frequency:

Digit Frequency
2 1
4 1
5 2
8 1

 


FlowChart


Please find the flowchart of program below –

 


Java Program


Please find java program to find frequency of the digit below –

package com.kw.sample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * This class helps to count frequency of the entered number.
 *
 * @author dsahu1
 *
 */
public class KWFrequencyOfNumber {

    /**
     * This method helps to execute program to find frequency of the digit.
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter any number : ");
        String num = br.readLine();

        int number = Integer.valueOf(num);
        // Instantiate an array to keep Digit with Frequency
        int freq[] = new int[10];
        // initialize default value to digit
        for (int i = 0; i < 10; i++) {
            freq[i] = 0;
        }
        int digit;
        // Calculate Digit with Frequency
        while (number > 0) {
            digit = number % 10;
            freq[digit]++;
            number = number / 10;
        }
        // Display Digit with Frequency
        System.out.println("Digit \t" + "Frequency");
        for (int i = 0; i < 10; i++) {
            if (freq[i] != 0) {
                System.out.println(i + "\t" + freq[i]);
            }

        }

    }

}


Output(s)


Once executed above program then you will find below output.

Scenario 1:

Enter any number : 45565222
Digit     Frequency
2    3
4    1
5    3
6    1

 

Scenario 2:

Enter any number : 455582005
Digit     Frequency
0    2
2    1
4    1
5    4
8    1


Video Explanation


This video helps to understand flowchart and program which written in the above steps. There are various ways to write a program and we are not covering all of them as this is just for practice. Please post your program in the comment box so other can utilize it.

 

Please click on below video to understand the problem with detailed explanation.

 

 

2 thoughts on “Java Program to find frequency of every digit in a number”

  1. Dear sir,

    Love you or may be actually thank you as I was breaking my head to understand the program given in my school text book as it made no sense.But when I found this site, I could easily understand. I didn’t copy the exact program given by you but modified it in my style and made it.
    Wish would get more helpful programs like this.

    Thank you

    Yours sincerely,
    ASHLESH

Leave a Reply

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