Coding Practice

Write a Java program to find frequency of each digit in a given integer

Find frequency of each digit in a given integers
Sample Output
Find frequency of each digit in a given integer.

Enter a number: 192002024
Frequency of 0 = 3
Frequency of 1 = 1
Frequency of 2 = 3
Frequency of 3 = 0
Frequency of 4 = 1
Frequency of 5 = 0
Frequency of 6 = 0
Frequency of 7 = 0
Frequency of 8 = 0
Frequency of 9 = 1
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int i, count, digit, number, numberClone;

        Scanner input = new Scanner(System.in);

        System.out.println("Find frequency of each digit in a given integer.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();

        numberClone = number;

        for (i = 0; i <= 9; i++) {
            count = 0;
            number = numberClone;

            while (number != 0) {
                
                digit = (number % 10);
                number = (number / 10);
                if (digit == i) {
                    count++;
                }
            }
            /// if(count > 0) /** This line will be print, if frequency is greater than 0.*/
            {
                System.out.println("Frequency of " + i + " = " + count);
            }
        }
    }
}
Sample Output
Find frequency of each digit in a given integer.

Enter a number: 2021
Frequency of 0 = 1
Frequency of 1 = 1
Frequency of 2 = 2
Frequency of 3 = 0
Frequency of 4 = 0
Frequency of 5 = 0
Frequency of 6 = 0
Frequency of 7 = 0
Frequency of 8 = 0
Frequency of 9 = 0

No comments:

Post a Comment

Change Theme
X