Count the number of digits in C
Now, we will look at how to count the number of digits in an integer. This integer is nothing but the number entered by the user.
First, we will calculate count the number of digits using for or while loop.
Let's create a program which will implement the above approach.
Now, we will see how to count the number of digits without using a loop.
We can also count the number of digits with the help of the logarithmic function. The number of digits can be calculated by using log10(num)+1, where log10() is the predefined function in math.h header file.
Let's see a simple example.
We will create a C program to count the number of digits using functions.
Now, we will see how to count the number of digits using recursion.
In the above program, we are calculating the number of digits in an integer. The func() function is called. In func(), we declare a static variable, i.e., counter, which will be initialized only once. The func(n/10) will be called recursive1y until the condition (n>0) is true. When the condition is false, then the value of the counter is returned.