Algorithm


  1. Input:

    • Accept an integer as input.
  2. Initialization:

    • Initialize a variable (count) to zero. This variable will be used to store the count of digits.
  3. Loop:

    • Use a loop (for or while) to iterate until the integer becomes zero.
    • Inside the loop:
      • Increment the count variable by 1.
      • Update the integer by dividing it by 10 (integer division).
  4. Output:

    • The value of count now represents the number of digits in the original integer.

 

Code Examples

#1 Code Example- Count Number of Digits in an Integer using while loop

Code - Java Programming

public class Main {

  public static void main(String[] args) {

    int count = 0, num = 0003452;

    while (num != 0) {
      // num = num/10
      num /= 10;
      ++count;
    }

    System.out.println("Number of digits: " + count);
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Number of digits: 4

#2 Code Example- Count Number of Digits in an Integer using for loop

Code - Java Programming

public class Main {

  public static void main(String[] args) {

    int count = 0, num = 123456;

    for (; num != 0; num /= 10, ++count) {
    }

    System.out.println("Number of digits: " + count);
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Number of digits: 6
Advertisements

Demonstration


Java Programing Example to Count Number of Digits in an Integer-DevsEnv