English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use while loop and for loop to calculate the number of digits in Java.
public class NumberDigits { public static void main(String[] args) { int count = 0, num = 3452; while(num != 0) { // num = num/10 num /= 10; ++count; } System.out.println("Number of digits: ", + count); } }
When running this program, the output is:
Number of digits: 4
In this program, the while loop will be used in a loop until the calculation result of the test expression num != 0 is 0(false).
After the first iteration, num will be divided by10, its value will be345. Then, count will be incremented to1.
After the second iteration, the value of num will be34, and count will be incremented to2.
After the third iteration, the value of num will be3, and count will be incremented to3.
After the fourth iteration, the value of num will be 0, and count will be incremented to4.
Then evaluate the test expression as false and terminate the loop.
public class NumberDigits { public static void main(String[] args) { int count = 0, num = 123456; for(; num != 0; num/=10, ++count) { } System.out.println("Number of digits: ", + count); } }
When running this program, the output is:
Number of digits: 6
In this program, instead of using a while loop, an empty for loop is used.
In each iteration, the value of num is divided by10, then count is incremented1.
If num != 0 is false, i.e., num = 0, the for loop exits.
Since the for loop has no body, it can be changed to a single statement in Java as follows:
for(; num != 0; num/=10, ++count);