GET EDUCATE

Contents
Basics of C Programming

⯈Basic C Programs

C program to count number of digits in a positive integer

The number of digits in a positive integer can be calculated using log10 function. (log to base 10)

Ex: N = 123, The number of digits in 123 is 3.

We know that,

log10(1) = 0

log10(10) = 1

log10(100) = 2

log10(1000) = 3

log10(10000) = 4

log10(100000) = 5

We can see that the number of digits from 0 to 9 is 1 and log10(1) and log10(9) lies between [0 , 1)

Similarly the number of digits from 100 to 999 is 3, and log10(100) and log10(999) lies between [2,3)

If we take the floor value of log10(N) and add 1 to it, we get the number of digits in the given positive number.

Reading the input,
scanf("%d",&n);

Calculating the number of digits,

d = floor(log10(N)) + 1

Program

#include<stdio.h>
#include<math.h
int main()
{
      int n;
    int d;
printf("Enter n:");
      scanf("%d",&n);
d = floor(log10(n)) + 1;
printf("Number of digits in %d = %d\n",n,d);
return 0;
}

Dry Run

Let N = 123,

d = floor(log10(123)) + 1

   = floor(2.08)+1

    = 2 + 1

d = 3

number of digits in positive number
Scroll to Top