Java program to count number of digits in an integer

Count number of digits in an integer using while loop

We can count the number of digits in a given number in many ways using java.

One of the approach is that, we shall take the number, remove the last digit, and increment our counter for number of digits in the number. We can continue this, until there is no digit in the number.

Another approach is that, we can convert the given number into a string, and use the method string.length() to count the number of character in this string. This results in the number of digits in given number.

Here, while the loop is iterated until the test expression number != 0 is evaluated to 0(false).

After the first iteration, number will be divided by 10 and its value will be 345. Then, the count is incremented to 1.

After the second iteration, the value of number will be 34 and the count is increased to 2.

After the third iteration, the value of number will be 3 and the count is increased to 3.

After the fourth iteration, the value of number will be 0 and the count is increased to 4.

Then the test expression is evaluated to false and the loop terminates.

  • Program:

public class Main {

  public static void main(String[] args) {

    int count = 0, number = 0003452;

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

    System.out.println("Number of digits: " + count);
  }
}

  • Output:

Number of digits: 4

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here 
Java program to find the largest among three numbers Here
Java program to find all roots of a quadratic equation Here
Java program to check leap year Here
Write a java program to multiply two floating point numbers Here
Java program to check whether a number is positive or negative Here
Java program to check whether a character is alphabet or not Here
Java program to calculate the sum of natural numbers Here
Java program to find factorial of a number Here
Java program to generate multiplication table Here
Write a java program to display Fibonacci series Here
Write a java program to find GCD of two numbers Here
Write a java program to find LCM of two numbers Here
Java program to display alphabets (A to Z) using loop Here

0 comments