Progress

# C program to count the number of Digits This post is part of the C programming code series which helps users to understand and learn C by examples. In this article, we will look into the C program to count the number of digits in any Integer.

Copy
``````#include <stdio.h>

int main(){
int num, count = 0;
printf("Enter the number\n");
scanf("%d", &num);
while(num>0){
count++;
num = num/10;
}
printf("Total digits count = %d\n",count);

}``````
Output
```Enter the number
46837
Total digits count = 5```

Now we will break the code into parts and try to understand what is going inside it.

Two integer type variables num and count are declared. We take the input and store them inside it.

The main logic of the c program to count the number of digits in an integer goes inside the while loop. The termination condition is defined as num>0. The variable count is incremented each time the loop runs.

The next line in the loop num = num/10 is the most important part here. It means after each loop removes the last digit. The loop terminates when num becomes 0, it means that every digit is counted.

Let’s understand the example step by step when the input is 46837.

• First Iteration: Count=1, num=46837/10 which means num=4683
• Second Iteration: Count=2, num=4683/10 which means num=46
• Third Iteration: Count=3, num=468/10 which means num=46
• Fourth Iteration: Count=4, num=46/10 which means num=4
• Fifth Iteration: Count=5, num=4/10 which means num=0
• Loop Terminates now as num is 0.

You may also Like:

Check a number is negative or positive in C.

Best Operating System for C programming Language

Share the Post ;)

Related Posts