Write a C program to count the digits in a number
Description: Take a number as input and print how many digits it has.
Hint:
- Divide the number by 10 in a loop, and count how many times you can do it before it becomes 0.
C program to count the digits of a number
#include <stdio.h>
int main(void) {
int n, count = 0;
printf("Enter a number: ");
scanf("%d", &n);
if (n == 0) {
count = 1;
}
while (n != 0) {
n /= 10;
count++;
}
printf("Number of digits = %d\n", count);
return 0;
}
Output:
Output of the above program is
Enter a number: 45678
Number of digits = 5
How it works
- 45678 becomes 4567, 456, 45, 4 and finally 0. That is 5 divisions, so 5 digits.
- The number 0 has one digit, so we handle it separately.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |