## Count digits program in C

In this count digits program we will take input from the user which is any integer and then we will count that how many digits are there in that integer.

If the user gives the input 12345 then we will print that “The number of digits is = 5“.

Obviously, we can write the code for serving this purpose in many way. You can try different way to write this program although we will discuss some mostly used way to write this program. Let’s go ahead with code.

## C program to count digits of an integer

Here, we will take the input from the user. Then we will create a loop which will execute till the value of that number is greater not equal to zero. Inside the loop we will divide the number by 10 which will give the integer portion of result. Let’s see in a program.

``````// count digits of an integer in C

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

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

mainNum = number;   // for printing purpose only

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

printf("\nTotal digits in %d is = %d\n", mainNum, counter);
return 0;
}``````

### Output of this count digits program : ## C count digits program without using loop

We will count the digits of a number without using loop in this program. We will use log10() library function which is under math.h header file. Let’s see the program.

``````// count digits program without using loop

#include <stdio.h>
#include<math.h>

int main(){
int number, counter = 0;
printf("Enter The number here : ");
scanf("%d",&number);

counter = (number == 0)?1:log10(number) + 1;
printf("\nNumber of digits is = %d\n",counter);
return 0;
}``````

### Count digits program output : ## Count digits program using recursion in C

We have told that you can write code for this program in many ways. Here in this program we will use recursion to count digits of a number given by the user. Let’s see once again.

``````// count digits program using recursion in C

#include <stdio.h>

int count_digits(int num);

int main(){
int number, counter = 0;
printf("Enter any number to count digits : ");
scanf("%d",&number);

counter = count_digits(number);

printf("\nTotal digits is = %d\n", counter);

return 0;
}

int count_digits(int num){
static int digit_count = 0;

if(num > 0){
digit_count = digit_count + 1;
return count_digits(num / 10);

}else{
return digit_count;
}

}``````

### Program output :

``````Enter any number to count digits : 5504536

Total digits is = 7``````

Now, you can try another way to count the digits of a number. You can make the same program using pointer, function or even preprocessor. So, try your own to make this program. This will really help you to increase your problem solving power.

Previous pagePascal triangle program

Next pageStrong number program