C program to count digits of a number using logarithms

  • Write a program in C to count digits of a number without using loops or conditional operator.
  • How to find number of digits in an integer using common logarithms.

To count the digits of a number, we can use common logarithms(base 10). Here is the formulae to find number of digits of a positive integer.

Digit count of N = (int)(log10(N) + 1)
As logarithm is only defined for positive numbers, we have to first convert negative numbers to positive numbers by multiplying then by -1.

For Example:
Digit count of 1234 = (int)(log(1234) + 1) = (int)(3.091 + 1) = 4

C program to count digits of a number using common logarithms

/*
 C Program to count number of digits in an integer in 
 one line 
*/
#include<stdio.h>
#include<math.h>

int main() {
    int num, digitCount;
    
    printf("Enter a positive integer\n");
    scanf("%d", &num);
    
    if(num < 0) num = num *-1;
    if(num){
       /* number of digit = log10(n) + 1 */
       digitCount = (int)log10((double)num) + 1;
    } else {
       digitCount = 1;
    }
    printf("Digit Count = %d", digitCount);
    return 0;
}
Output
Enter an integer
2345
Digit Count = 4
Enter an integer
-234
Digit Count = 3
Enter an integer
0
Digit Count = 1