Control Flow
Java Program to Count Number of Digits in an Integer
A Java program to count the number of digits in an integer.
Problem Description
Write a Java program to count the number of digits in an integer entered by the user.
Code
public class CountDigits {
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);
}
}Output
Number of digits: 4Explanation
- Loop: Runs while
numis not 0. - Division: Divides
numby 10 in each iteration to remove the last digit. - Counter: Increments
countin each iteration.
