๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

WAP to count the number of digits in a number in Java  


Logical Steps:
  • Take one number and set a counter variable to 0 to keep track of the number of digits.
  • Use a loop:
    • Divide the number by 10 in each iteration.
    • Increment the counter until the number becomes 0.
  • Print the counter as the digit count.
Programs:
  • Below is the simple program:
    public class DigitCounter
    {
        public static void main(String[] args)
        {
            int no = 1382;
            int count = 0;
    
            while (no != 0)
            {
                no = no / 10;
                count++;
            }
    
            System.out.println("The number of digits is: " + count);
        }
    }
    Output:
    The number of digits is: 4
  • Below is the program by taking user input:
    import java.util.Scanner;
    
    public class DigitCounter
    {
        public static void main(String[] args)
        {
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Enter a number: ");
            int no = scanner.nextInt();
            int count = 0;
    
            while (no != 0)
            {
                no = no / 10;
                count++;
            }
    
            System.out.println("The number of digits is: " + count);
            scanner.close();
        }
    }
    Output:
    Enter a number: 72513
    The number of digits is: 5
Program Explanation
  • Take input from the user using Scanner and store it in an integer variable no.
  • Initialize a counter count = 0. This variable will track the number of digits.
  • Use a while loop to iterate until no becomes 0.
    • In each iteration, divide no by 10 (no = no/10;) to remove the last digit.
    • Increment count by 1 (count++) to record that a digit has been counted.
  • When the loop ends, the count variable will hold the total number of digits in the input number.
  • Display the result using System.out.println("The number of digits is: " + count);.