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

C
#include <stdio.h>

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

    printf("Enter a number: ");
    scanf("%d", &num);

    if(num == 0) {
        count = 1;
    } else {
        while(num != 0) {
            num /= 10;
            count++;
        }
    }

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

    return 0;
}

Sample Output

Enter a number: 12345
Number of digits = 5

Explanation

  • Each iteration divides the number by 10 to remove its last digit.
  • The variable `count` keeps track of the total iterations performed.
  • When the number becomes 0, the loop stops, and `count` holds the total digits.
  • For example, 12345 → 1234 → 123 → 12 → 1 → 0 → total 5 digits.
Note: Note: If the entered number is 0, it should count as a single digit. This is handled in the program logic.