Program to count the no of digits in a number
Counting the number of digits in a number is a common beginner-level program in C. This helps in understanding how to use loops and arithmetic operations like division.
#include <stdio.h>
int main() {
int num, count = 0;
// Input from user
printf("Enter a number: ");
scanf("%d", &num);
// Handle 0 separately
if (num == 0) {
count = 1;
} else {
while (num != 0) {
num = num / 10; // Remove the last digit
count++; // Increment digit count
}
}
printf("Number of digits: %d\n", count);
return 0;
}
OUTPUT
Enter a number: 12345
Number of digits: 5
Explanation:
-
The user is asked to input a number.
-
A
whileloop is used to divide the number by 10 repeatedly, removing one digit in each step. -
For every division, the
countis incremented. -
Special handling is done for
0, which has 1 digit.


