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
whileloop is used to iterate as long as the value ofnis greater than0. -
Inside the loop:
-
The
countvariable is incremented by1in each iteration. This is done to keep track of the number of digits. -
The value of
nis divided by10. This operation effectively removes the rightmost digit from the number. For example, ifnis123, after this division,nbecomes12.
-
-
The loop continues executing as long as the condition
n > 0remains true. Oncenbecomes0or 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.hand the math librarymath.h, which contains mathematical functions likelog10andfloor. -
Now declare two integers: n, len
-
The
lenvariable 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
1tofloor(log10(n))compensates for the fact that we subtracted1to 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!