JAVA PROGRAM 3
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
ALGORITHM
Step1:
Start.
Step2:
Accept a number from user in integer variable ‘n’.
Step3:
Declare an integer array of size 10 and assign 0 to all 10 elements of array
statically.
Step4:
Take a loop which runs until n is greater than zero because after each
iteration n is reduced by one digit.
Step5:
Declare integer variable ‘rem’ to find remainder of n using modulo operator
(n%10). The resulting remainder is last digit of n.
Step6:
Since there are only 10 different digits increment the array element which corresponds
to digit stored in variable ‘rem’.
Step7:
Divide n by 10 to reduce it by one digit.
Step8:
Repeat steps 5-7 to count frequency of all digits present in n until it is
reduced to 0.
Step9:
Take a loop ranging from 0 to 10. Check if each element of array is non-zero
because it is not necessary to display frequency of digits which are not
present.
Step10:
Display the digit and its corresponding frequency in given format.
Step11:
Stop.
PROGRAM:
import
java.util.*;
class
frequency
{
Scanner sc=new Scanner (System.in);
void main()
{
System.out.print("Sample Input:
");
int n=sc.nextInt();
int a[]=new int [10];
for(int i=0;i<10;i++)
{
a[i]=0;
}
while(n>0)
{
int rem=n%10;
a[rem]++;
n=n/10;
}
System.out.println("Sample output:
");
System.out.println("-------------------------");
System.out.println("-------------------------");
System.out.println("Digit\t\tFrequency");
System.out.println("-------------------------");
System.out.println("-------------------------");
for (int i = 0; i < 10; i++) {
if (a[i] != 0) {
System.out.println(i +
"\t\t" + a[i]);
}
}
}}
Sample
input/output:
Random input/output:
Comments
Post a Comment