Write a C program to read an integer from user and count total number of digits the integer contains. 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 using C program.
Example:
Input num: 35419
Output digits: 5
First is the easiest method to count number of digits in an integer.
Happy coding ;)
Example:
Input num: 35419
Output digits: 5
Required knowledge
Basic C programming, LoopLogic to count number of digits in an integer
There are plenty of ways through which you can count the number of digits in a given integer. Here we will be looking two of the methods through which we can find the number of digits in an integer.First is the easiest method to count number of digits in an integer.
- Initialize a variable count to 0.
- Increment count by 1 if num > 0 (where num is the number whose digits count is to be found).
- Remove the last digit from the number as it isn't needed anymore. Hence divide the number by 10 i.e num = num / 10.
- If number is greater than 0 then repeat steps 2-4.
Program to count number of digits in an integer
/**
* 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; // num = num / 10
}
printf("Total digits: %d", count);
return 0;
}
Now, lets take a look to the second method of finding total number of digits in a given integer using mathematical approach. This method is more simpler and shorter to use. Before using this method you must have a good knowledge of logarithms.
Program to find number of digits in an integer
/**
* C program to count number of digits in an integer
*/
#include <stdio.h>
#include <math.h>
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;
}
Output
Enter any number: 123456789
Total digits: 9
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.