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.

Approach

  • Firstly, the number will be entered by the user. Suppose we declare the variable 'n' and stores the integer value in the 'n' variable.
  • We will create a while loop that iterates until the value of 'n' is not equal to zero.
  • Suppose the value of 'n' is 123.
  • When the first iteration executes, the value of 'n' will be 123, and the value of count will be incremented to 1.
  • When the second iteration executes, the value of 'n' will be 12, and the value of count will be incremented to 2.
  • When the third iteration executes, the value of 'n' will be 1, and the value of count will be incremented to 3.
  • After the completion of the third iteration, the value of 'n' becomes 0, and loop is terminated as it does not satisfy the condition (n!=0).

Let's create a program which will implement the above approach.

Output

Count the number of digits in C

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.

Output

Count the number of digits in C

We will create a C program to count the number of digits using functions.

Output

Count the number of digits in C

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.

Output

Count the number of digits in C