PROGRAM 11 : TO FIND THE DIGIT FREQUENCY , THAT IS THE NUMBER OF TIMES A DIGIT HAS APPEARED IN THE NUMBER.
EXAMPLE :
PROGRAM :
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 : ");
String num = br.readLine();
System.out.println("Output:");
System.out.println("====================");
System.out.println("Digit\tFrequency");
System.out.println("====================");
System.out.println();
int count = 0;
char ch;
for(int i = 48 ; i<=57 ; i++) // THE ASCII VALUES OF '0' TO '9'(48 TO 57)
{ ch = (char)i; // CONVERTS THE ASCII VALUE TO CHARACTER
for(int j = 0 ; j<num.length() ; j++)
{
if(num.charAt(j)==ch) // CHECKS OCCURRENCES OF THE DIGIT IN THE WHOLE NUMBER
count++; // INCREASES COUNT BY '1'
}
if(count>0){ // DISPLAYS ONLY THE DIGITS THAT ARE IN THE NUMBER
System.out.print(ch+ " " + count);
System.out.println();
}
count = 0; // COUNT IS MADE ZERO SO THAT IT CHECKS THE OCCURRENCES OF NEXT DIGIT
}
}
}
EXAMPLE :
PROGRAM :
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 : ");
String num = br.readLine();
System.out.println("Output:");
System.out.println("====================");
System.out.println("Digit\tFrequency");
System.out.println("====================");
System.out.println();
int count = 0;
char ch;
for(int i = 48 ; i<=57 ; i++) // THE ASCII VALUES OF '0' TO '9'(48 TO 57)
{ ch = (char)i; // CONVERTS THE ASCII VALUE TO CHARACTER
for(int j = 0 ; j<num.length() ; j++)
{
if(num.charAt(j)==ch) // CHECKS OCCURRENCES OF THE DIGIT IN THE WHOLE NUMBER
count++; // INCREASES COUNT BY '1'
}
if(count>0){ // DISPLAYS ONLY THE DIGITS THAT ARE IN THE NUMBER
System.out.print(ch+ " " + count);
System.out.println();
}
count = 0; // COUNT IS MADE ZERO SO THAT IT CHECKS THE OCCURRENCES OF NEXT DIGIT
}
}
}
No comments:
Post a Comment