Hello readers, In this article, I will teach you how to get the length of any number in C.
There are two ways to reach our goal 🎯:
-
Using loop
-
Using <math.h>
I will share both the methods in this article.
Method 1: Using Loop
-
Here are the steps you need to follow:
-
Declare an integer n;
-
A
while
loop is used to iterate as long as the value ofn
is greater than0
. -
Inside the loop:
-
The
count
variable is incremented by1
in each iteration. This is done to keep track of the number of digits. -
The value of
n
is divided by10
. This operation effectively removes the rightmost digit from the number. For example, ifn
is123
, after this division,n
becomes12
.
-
-
The loop continues executing as long as the condition
n > 0
remains true. Oncen
becomes0
or negative, the loop will terminate.
#include <stdio.h>
int main(){
int n;
printf("Enter a number: ");
scanf("%d",&n);
int count;
while(n>0){
count++;
n = n / 10;
}
printf("No. of digits = %d", count);
return 0;
}
Method 2: Using <math.h>
For this method, here are the steps you need to follow:
-
The code includes the standard input- output library
stdio.h
and the math librarymath.h
, which contains mathematical functions likelog10
andfloor
. -
Now declare two integers: n, len
-
The
len
variable is assigned a value using the following expression:-
log10(n)
calculates the base- 10 logarithm of the input numbern
. This effectively gives the exponent that, when raised to the power of 10, results in the input number. -
floor(log10(n))
takes the floor of the logarithmic value to ensure we have a whole number. This operation effectively counts the number of digits minus one in the input number. -
Adding
1
tofloor(log10(n))
compensates for the fact that we subtracted1
to find the number of digits. This gives us the actual count of digits.
-
#include<stdio.h>
#include<math.h>
int main(){
int n, len;
printf("Enter a number: ");
scanf("%d", &n);
len = floor(log10(n))+1;
printf("No. of digits = %d\n", len);
return 0;
}
So, this is how you can get the length of the number in C Language.
Hope you have a great day!
Thanks for reading!