Java Program to Count Digits of a Number

Here is a simple Java program that counts the number of digits in a given integer:

Problem

Here is example of the problem  –

Enter an Number : 12345
Number of digits in 12345 : 5

Algorithm:

  1. Start program,
  2. Read or input a number,
  3. declare an integer variable count initialize it with 0,
  4. Divide the number with 10 till the number is 0, and for each turn increase the count.

Code:

import java.util.Scanner;

public class NumberOfDigits {	
    public static void main(String[] args) {
        int Number;
        int count=0;
         Scanner sc = new Scanner(System.in);		
        System.out.println("Enter any Number: ");
        Number = sc.nextInt();
        
        while(Number > 0) {
            Number = Number / 10;
            count++;
        }
        System.out.println("Number of digits in a given number is  "+count);
    }
}

Output:

 Enter any Number: 
1234
Number of digits in a given number is 4

More java Programs:

Leave a Comment

%d bloggers like this: