To count the digits in an integer, repeatedly divide the value by 10 until it becomes zero. Remember that 0 itself contains one digit and that a minus sign is not a digit.
#include <stdio.h>
int count_digits(int number) {
int count = 0;
do {
count++;
number /= 10;
} while (number != 0);
return count;
}
int main(void) {
int number;
printf("Enter an integer: ");
if (scanf("%d", &number) != 1) {
printf("Invalid input.\n");
return 1;
}
printf("Number of digits = %d\n", count_digits(number));
return 0;
}
For example, 2341 has 4 digits. If the user types 0342 as an integer, the stored numeric value is 342, so the result is 3.
The original page demonstrated conversion to a string. With a negative number, subtract the leading minus sign from the text length.
#include <stdio.h>
#include <string.h>
int main(void) {
int number = -2341;
char text[32];
int written = snprintf(text, sizeof text, "%d", number);
if (written < 0 || (size_t)written >= sizeof text) {
printf("Conversion failed.\n");
return 1;
}
size_t digits = strlen(text);
if (text[0] == '-') {
digits--;
}
printf("Number of digits = %zu\n", digits);
return 0;
}
#include <stdio.h>
int count_digits(int number) {
if (number > -10 && number < 10) {
return 1;
}
return 1 + count_digits(number / 10);
}
int main(void) {
int number = 12345;
printf("Number of digits: %d\n", count_digits(number));
return 0;
}
Output
Number of digits: 5
#include <stdio.h>
int main(void) {
int number = 123456;
int even = 0;
int odd = 0;
do {
int digit = number % 10;
if (digit < 0) {
digit = -digit;
}
if (digit % 2 == 0) {
even++;
} else {
odd++;
}
number /= 10;
} while (number != 0);
printf("Even digits: %d, Odd digits: %d\n", even, odd);
return 0;
}
Output
Even digits: 3, Odd digits: 3
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.