# Count the number of digits in C

#### 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.

#include <stdio.h>

int main()

{

int n;  // variable declaration

int count=0;   // variable declaration

printf(“Enter a number”);

scanf(“%d”,&n);

while(n!=0)

{

n=n/10;

count++;

}

printf(“\nThe number of digits in an integer is : %d”,count);

return 0;

}

Output

Now, we will see how to count the number of digits without using a loop.