Count Digits of a Number | Write a program in Java to count the digits in a number. | ISC Computer Science | ICSE Computer Applications
Algorithm
- Start
- n:=0
- d:=0
- Print "Enter a number"
- Read n
- d=0
- If n>0, go to step 8 or else go to step 10
- d++
- n=n/10
- Go to step 7
- Print "The number of digits in the given number is "+d
- Stop
Program
Buffered Reader
import java.io.*;
class CountDigits
{
int n,d;
void accept() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
System.out.println("Enter a number");
n=Integer.parseInt(br.readLine());
}
void count()
{
d=0;
while (n>0)
{
d++;
n=n/10;
}
}
void display()
{
System.out.println("The number of digits in the given number is "+d);
}
void main() throws IOException
{
accept();
count();
display();
}
}
Scanner
import java.util.*;
class CountDigits
{
int n,d;
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
n=sc.nextInt();
}
void count()
{
d=0;
while (n>0)
{
d++;
n=n/10;
}
}
void display()
{
System.out.println("The number of digits in the given number is "+d);
}
void main()
{
accept();
count();
display();
}
}
Documentation
Variable Description
Data Type | Variable Name | Description |
int | n | To store the number entered by the user |
int | d | To store the number of digits in the number |
Method Description
Return Type | Method Name | Description |
void | accept() | To accept data from the user |
void | count() | To count the number of digits in a number |
void | display() | To display the result of the program |
void | main() | To act as an entry gateway for the compiler |
Output
Share with all ISC Computer Science Students you know.
Comment below with all your program requests and blog suggestions.
Follow us on social media by clicking on these links.
Instagram : @ISCJavaCode
Twitter: @ISCJavaCode
Quora: ISC Java Code
Reddit: @ISCJavaCode
Stay Healthy
Stay Happy
Stay Helpful
Comments
Post a Comment