Write a C program to count number of digits in an integer. How to find total number of digits in a given integer using loop in C programming. Logic to count number of digits in a given integer without using loop in C program.

**Example**

**Input**

Input num: 35419

**Output**

Number of digits: 5

## Required knowledge

## Logic to count number of digits in an integer

There are various logic to count number of digits in an integer. Today I will explain two logic to count number of digits, using loop and without using loop. First logic is the easiest and is the common to think. It uses loop to count number of digits.

Logic to count number of digits in given integer using loop.

- Read a number from user. Store it in some variable say num.
- Initialize another variable with 0 say digit = 0.
- Copy the value of num to some temporary variable say temp = num.
- If temp > 0 then increment the value of count by 1 i.e. count = count + 1.
- Divide temp by 10 to remove last digit i.e. temp = temp / 10.
- Repeat step 4-5 till temp > 0 or temp != 0.

## Program to count number of digits in an integer using loop

/** * C program to count number of digits in an integer */ #include <stdio.h> int main() { long long num; int count = 0; printf("Enter any number: "); scanf("%lld", &num); while(num != 0) { count++; num /= 10; } printf("Total digits: %d", count); return 0; }

## Logic to count number of digits without using loop

As I talked earlier let us now move on to our second logic to compute number of digits. It uses mathematical approach. It is simpler and shorter to use. Before I formally discuss this method you must have a good knowledge of logarithms.

For this logic we will make use of log10(x) function. It returns the logarithm of x to the base 10. It basically returns total number of digits - 1. Hence to get total number of digit you can use log10(x) + 1. Let us now implement this.

## Program to count number of digits without using loop

/** * C program to count number of digits in an integer without loop */ #include <stdio.h> #include <math.h> //Used for log10() int main() { long long num; int count = 0; printf("Enter any number: "); scanf("%lld", &num); count = log10(num) + 1; printf("Total digits: %d", count); return 0; }

Enter any number: 123456789 Total digits: 9

Happy coding ;)

### You may also like

- Loop programming exercises index.
- C program to find first and last digit of any number.
- C program to find sum of digits of any number.
- C program to find product of digits of any number.
- C program to swap first and last digits of any number.
- C program to find sum of first and last digit of any number.
- C program to print a given number in words.

< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)