C Program to Count Digits in a Number

This program counts and displays the total number of digits in a given integer using a simple while loop and division operation.

Concept Overview

To count digits, we divide the number by 10 repeatedly until it becomes 0. Each division removes one digit from the number, and we count how many times this process occurs.

Program

#include <stdio.h>

int main() {
    int num, count = 0;

    // Input from user
    printf("Enter a number: ");
    scanf("%d", &num);

    // Handle zero separately
    if (num == 0) {
        count = 1;
    } else {
        // Convert negative to positive
        if (num < 0)
            num = -num;

        // Count digits
        while (num != 0) {
            num = num / 10;
            count++;
        }
    }

    printf("Number of digits = %d\n", count);
    return 0;
}

Sample Output

Enter a number: 12345
Number of digits = 5

Explanation