Count the Number of Digits in C

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.

Count Digits with Integer Division Top ↑

#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.

Count Digits by Converting to Text Top ↑

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;
}

Recursive Digit Count Top ↑

#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

Count Even and Odd Digits Top ↑

#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




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer