How To Count Number Of Digits Of An Integer In C: Algorithm And The Program

Finding the total number of digits of an integer is a basic exercise given to every beginner of programming. In this article I will discuss the algorithm as well as provide the code utilizing that.


The Algorithm
The algorithm is very simple. First we will initialize a counter with zero. Then given the integer we need to divide it by 10 (integer division) and add 1 to the counter. We will carry on the same process till the dividend remains greater than zero. This algorithm will work for positive integers and to take care of negative numbers we will simply

replace the negative integer by the positive one.
But this algorithm has a little flaw since it will not work for zero (which is considered to have length 1) so to make an improvement we will initialize the counter by 1 and run the loop of integer division till the number remains greater than 9. This will also decrease one step in the loop and thus reduce run time.


The C Program
 The code provided below will take an integer from user as input and give out the length of it.


#include<stdio.h>
#include<math.h>
/**** ---- Main ---- ****/
int main()
{
long n;
printf("Enter a number: ");
scanf("%ld",&n);
printf("Number of digits: ");
printf("%ld",digit_count(n));
}
/**** ---- End of main ---- ****/

/**** ---- Function to count digits ---- ****/
int digit_count(int n)

/> {
if(n==0)
return 1; // n=0 has l_arr 1 //
int digit_no=1,i;
n=abs(n); // Including negative numbers //
for(i=n;i>9;i/=10)
digit_no++;
return(digit_no);
}
/**** ---- End of digit_count ---- ****/


I have done the counting by calling a function “digit_count” in which the variable “digit_no” is the counter. The utility of using function is that it can be inserted in any other program for finding length of an integer.
Hope this will be helpful for the beginners of C programming.

Check out my other articles on programming.

How to Convert a Decimal Number into Arbitrary Base: A “C” Program

Handling Large Numbers in C: A Tutorial to Find Large Exponentiation of a Number

If you like to join ExpertsColumn click here.



Article Written By roytanay

Last updated on 28-07-2016 2K 0

Please login to comment on this post.
There are no comments yet.
How To Convert A Decimal Number To Any Fractional Base: A Tutorial