dhairyashah
Portfolio

Aug 26th, 2023

How to get the length of a number in C?

Author Picture

Dhairya Shah

Software Engineer

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 🎯:

I will share both the methods in this article.

Method 1: Using Loop

#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:

#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!