π Introduction
Counting the number of digits in a number is one of the basic Java number programs. This program is commonly asked in BCA exams, practicals, and interviews.
In this article, you will learn how to count the number of digits in Java using a simple loop.
❓ What Does “Count Number of Digits” Mean?
It means finding how many digits are present in a given number.
Example
Number:
12345Number of digits:
5
π§ Logic Used
Each time we divide the number by
10, one digit is removedWe increase the counter for every division
Loop continues until the number becomes
0
π§© Algorithm to Count Number of Digits
Start
Read a number
Initialize
count = 0While number ≠ 0
count++
number = number / 10
Print count
End
π» Java Program to Count Number of Digits
import java.util.Scanner;
public class CountDigits {
public static void main(String[] args) {
int number, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
number = sc.nextInt();
while (number != 0) {
count++;
number = number / 10;
}
System.out.println("Number of digits: " + count);
}
}
π§ͺ Dry Run
Input
number = 4567
count = 0
| Step | number | count |
|---|---|---|
| 1 | 4567 | 1 |
| 2 | 456 | 2 |
| 3 | 45 | 3 |
| 4 | 4 | 4 |
Final Output
Number of digits: 4
π₯️ Output
Enter a number: 4567
Number of digits: 4
π Special Case: Number = 0
π 0 has 1 digit, but the loop will not run.
Solution for This Case
if (number == 0) {
count = 1;
}
π― Important Points for Exams
/ 10removes one digitLoop runs once per digit
Time Complexity: O(n)
Works for all positive numbers
Comments
Post a Comment