This java program to Count Total Number of Digits in an Integer. We are using while loop approach.
- Here we iterate while loop until the method expression num != 0 is given to 0 (false).
- At the first iteration, num will be divided by 10 and its value will be 1234, then the count is incremented to 1.
- Now the second iteration, the value of num will be 123 and the count is incremented to 2.
- After the third iteration, the value of num will be 12 and the count is incremented to 3.
- After the fourth iteration, the value of num will be 1 and the count is incremented to 4.
- After the fifth iteration, the value of num will be 0 and the count is incremented to 5.
- Then the test expression num!=0 is evaluated to false and the loop terminates.
- Now print the Total Number of Digits in an Integer.
public class CountOfDigit {
public static void main(String[] args) {
int num = 12345;
int count = 0;
while (num != 0) {
num = num / 10;
count++;
}
System.out.println("Total number of digit: "+count);
}
}
Output :-
Total number of digit: 5