Task: Read an integer and count its digits by repeated division by 10. Handle zero (1 digit) and negative numbers correctly.
/*
Program: Count Digits in an Integer (U2)
What it does:
- Reads an integer n; counts how many digits it has.
- Treats 0 as a 1-digit number; handles negatives by ignoring sign.
*/
#include <stdio.h>
int main(void) {
int n, tmp, count = 0;
printf("Enter an integer: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input.
");
return 0;
}
if (n == 0) {
count = 1;
} else {
tmp = (n < 0) ? -n : n;
while (tmp > 0) { tmp /= 10; ++count; }
}
printf("Digits = %d
", count);
return 0;
}