How to get the length of a number in C?

Aug 26th, 2023

How to get the length of a number in C?

advertisement

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 of n is greater than 0.

  • Inside the loop:

    • The count variable is incremented by 1 in each iteration. This is done to keep track of the number of digits.

    • The value of n is divided by 10. This operation effectively removes the rightmost digit from the number. For example, if n is 123, after this division, n becomes 12.

  • The loop continues executing as long as the condition n > 0 remains true. Once n becomes 0 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 library math.h, which contains mathematical functions like log10 and floor.

  • 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 number n. 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 to floor(log10(n)) compensates for the fact that we subtracted 1 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!