Algorithm
-
Input:
- Accept an integer as input.
-
Initialization:
- Initialize a variable (
count
) to zero. This variable will be used to store the count of digits.
- Initialize a variable (
-
Loop:
- Use a loop (for or while) to iterate until the integer becomes zero.
- Inside the loop:
- Increment the
count
variable by 1. - Update the integer by dividing it by 10 (integer division).
- Increment the
-
Output:
- The value of
count
now represents the number of digits in the original integer.
- The value of
Code Examples
#1 Code Example- Count Number of Digits in an Integer using while loop
Code -
Java Programming
public class Main {
public static void main(String[] args) {
int count = 0, num = 0003452;
while (num != 0) {
// num = num/10
num /= 10;
++count;
}
System.out.println("Number of digits: " + count);
}
}
Copy The Code &
Try With Live Editor
Output
Number of digits: 4
#2 Code Example- Count Number of Digits in an Integer using for loop
Code -
Java Programming
public class Main {
public static void main(String[] args) {
int count = 0, num = 123456;
for (; num != 0; num /= 10, ++count) {
}
System.out.println("Number of digits: " + count);
}
}
Copy The Code &
Try With Live Editor
Output
Number of digits: 6
Demonstration
Java Programing Example to Count Number of Digits in an Integer-DevsEnv