Frequency of each digit of a number in Java
Frequency of each digit of a Number
Question : Write a program to count and display the frequency of each digit of a number.
For Example :-
Input : 19224
Output : Frequency of 1 is : 1
Frequency of 2 is : 2
Frequency of 4 is : 1
Frequency of 9 is : 1
Input : 1113
Output : Frequency of 1 is : 3
Frequency of 3 is : 1
Program to count & display Frequency of each digit of a Number :-
Program :-
import java.io.*;
import java.util.*;
class Digit
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n,p,dig,i;
int digit[] = new int[10];
System.out.println("Enter Number");
n = in.nextInt();
p=n;
while(p>0)
{
dig = p%10;
for(i=0;i<=9;i++)
{
if(dig==i)
{
digit[i]++;
}
}
p=p/10;
}
System.out.println("Original Number : "+n);
for(i=0;i<=9;i++)
{
if(digit[i]!=0)
{
System.out.println("Frequency of "+i+" is : "+digit[i]);
}
}
}// end of main method
}// end of class
Program to count & display Frequency of a particular digit of a Number :-
Program :-
import java.io.*;
import java.util.*;
class Digit
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n,p,dig,i,digit,c=0;
System.out.println("Enter Number");
n = in.nextInt();
p=n;
System.out.println("Enter Digit whose frequency is required");
digit = in.nextInt();
while(p>0)
{
dig = p%10;
if(dig==digit)
{
c++;
}
p=p/10;
}
System.out.println("Original Number : "+n);
System.out.println("Frequency of "+digit+" is : "+c);
}// end of main method
}// end of class
All the best :)
Keep Learning :)
Comments
Post a Comment