# C Program to Count Number of Digits in an Integer

Write a C program to count the number of digits in an integer using for loop, while loop, without using recursion, and using recursion.

If we take the number 985632, it has 6 digits. For count number of digits, declare a count variable and initialize it with 0. Divide the number by 10 and then increase the count value, repeat this process. When the number becomes 0 then stop the process.

Prerequisites:- While loop in C, For loop in C

## Count the Number of Digits in an Integer using the while loop

`````` #include<stdio.h>
int main()
{
int number, count=0;

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

while (number!=0)
{
count++;
number /= 10;
}

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

return 0;
}``````

Output:-

Enter a number: 12586
Number of digits = 5

## Using for loop

The for loop decrease the lines of code used in the previous program. The initialization, condition, and update expression are placed at a single place so for loop make program cleaner.

`````` #include<stdio.h>
int main()
{
int number, count;

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

for(count=0; number!=0; number /= 10)
{
count++;
}

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

return 0;
}``````

## C Program to Count the Number of Digits in an Integer without using a loop

We can use `strlen()` function to count the number of digits in an integer without using the loop. The strlen() function is defined under “string.h” header file and it returns the number of characters of a string.

`````` #include<stdio.h>
#include<string.h>
int main()
{
int number;
char ch;

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

sprintf(ch, "%d", number);

printf("Number of digits =  %ld\n", strlen(ch));

return 0;
}``````

## Count the Number of Digits in an Integer using Recursion

Instead of using a pre-defined function, we can write our own function to count the number of digits in an integer. Below `numberOfDigits()` is a recursive function, which calls itself when the number is not equal to zero.

`````` #include<stdio.h>
int numberOfDigits(int n)
{
return n==0? 0 : 1+numberOfDigits(n/10);
}
int main()
{
int number, sum;

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

sum = numberOfDigits(number);

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

return 0;
}``````

The recursive function `numberOfDigits()` returns 0 if the number is 0, else it calls itself from the expression `1+numberOfDigits(n/10)`. In every call, the number is divided by zero and then it is passed as an argument.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Also See:-