OverIQ.com

C Program to count number of digits in a number

Last updated on September 23, 2020


The following is a C program to count the number of digits in a number.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/****************************************************
 * Program to count the number of digits in a number
*****************************************************/

#include<stdio.h> // include stdio.h

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

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

    while (num != 0) 
    {
        rem = num % 10;  // get the last digit of num
        num = num / 10;  // remove the last digit from num
        count++;         // increment count by 1
    }

    printf("%d", count);

    return 0;
}

Try it now

Expected Output: 1st run:

1
2
Enter a number: 123456
6

2nd run:

1
2
Enter a number: 25
2

How it works #

The following table demonstrates what happens at each iteration of the loop, assuming num = 123456.

Iteration rem num count
After 1st iteration rem = 123456%10 = 6 n = 123456/10 = 12345 count = 1
After 2nd iteration rem = 12345%10 = 5 n = 12345/10 = 1234 count = 2
After 3rd iteration rem = 1234%10 = 4 n = 1234/10 = 123 count = 3
After 4th iteration rem = 123%10 = 3 n = 123/10 = 12 count = 4
After 5th iteration rem = 12%10 = 2 n = 12/10 = 1 count = 5
After 6th iteration rem = 1%10 = 1 n = 1/10 = 0 count = 6

Recommended Reading: