Count Digits of a Number | Write a program in Java to count the digits in a number. | ISC Computer Science | ICSE Computer Applications

Count Digits of Number

Algorithm

  1.   Start
  2. n:=0
  3. d:=0
  4. Print "Enter a number"
  5. Read n
  6. d=0
  7. If n>0, go to step 8 or else go to step 10
  8. d++
  9. n=n/10
  10. Go to step 7
  11. Print "The number of digits in the given number is "+d
  12. 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 NameDescription
 intTo store the number entered by the user 
 intTo store the number of digits in the number 

Method Description

Return Type Method NameDescription
 voidaccept() To accept data from the user  
 voidcount() To count the number of digits in a number 
 voiddisplay() To display the result of the program 
 voidmain() To act as an entry gateway for the compiler  

Output

Output of Digit Count





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
Reddit: @ISCJavaCode
Pinterest: @ISCJavaCode
Facebook: @ISCJavaCode
LinkedIn : ISC Java Code 


Stay Healthy
Stay Happy
Stay Helpful



Comments

You might also like:

Conversion of Complex Sentences to Simple Sentences

Conversion of Compound Sentences to Complex Sentences.

Conversion of Complex Sentences to Compound Sentences