Count Digits of an Integer in Java

Exercise:

Write a Java Program to count number of digits in an integer.

1.Count using For Loop

Click Here to View the Solution!
public class DigitCounter {
  
   public static void main(String[] args) {
  
     int count = 0, num = 9875634;
  
     for (; num != 0; num /= 10, ++count) {
     }
  
     System.out.println("Number of digits in the entered number: " + count);
   }
} 
Click Here to View the Output!
Number of digits in the entered number: 7
Click Here to View the Explanation!
  • This program is used to count the number of digits in an integer number by using a for loop and display the number of digits.
  • Like the above program where a while loop is used, this program uses a for loop that requires no body.
  • The integer variable count and num are initialized like the previous program.
  • In every iteration of the for loop, the value in num is divided by 10 and one is incremented into the variable count.
  • A condition is checked of whether num is still not equal to zero (true). When this condition becomes false, the loop ends, and the number of digits are printed.
  • Unlike the while loop, the for loop can be changed into a single statement since, for loop is without a body as follows: for(; num != 0; num/10; ++count).

2.Count Using while loop

Click Here to View the Solution!
public class DigitCounter{
 
 public static void main(String[] args) {
  
     int count = 0, num = 8124;
  
     while (num != 0) {
       // num = num/10
       num /= 10;
       ++count;
     }
  
     System.out.println("Number of digits: " + count);
   }
}  
Click Here to View the Output!
Number of digits: 4
Click Here to View the Explanation!
  • This program is used to count the number of digits in an integer number by using a while loop and display the number of digits.
  • Like the above program where a while loop is used, this program uses a while loop that requires no body.
  • The integer variable count and num are initialized like the previous program.
  • In every iteration of the while loop, the value in num is divided by 10 and one is incremented into the variable count.
  • A condition is checked of whether num is still not equal to zero (true). When this condition becomes false, the loop ends, and the number of digits are printed.