C Program to Count Digits in a Number
This program counts and displays the total number of digits in a given integer using a simple while loop and division operation.
Concept Overview
To count digits, we divide the number by 10 repeatedly until it becomes 0. Each division removes one digit from the number, and we count how many times this process occurs.
Program
#include <stdio.h>
int main() {
int num, count = 0;
// Input from user
printf("Enter a number: ");
scanf("%d", &num);
// Handle zero separately
if (num == 0) {
count = 1;
} else {
// Convert negative to positive
if (num < 0)
num = -num;
// Count digits
while (num != 0) {
num = num / 10;
count++;
}
}
printf("Number of digits = %d\n", count);
return 0;
}
Sample Output
Enter a number: 12345 Number of digits = 5
Explanation
- Each iteration divides the number by 10 to remove its last digit.
- The variable `count` keeps track of the total iterations performed.
- When the number becomes 0, the loop stops, and `count` holds the total digits.
- For example, 12345 → 1234 → 123 → 12 → 1 → 0 → total 5 digits.