Software & Finance





Turbo C - Count Number of Digits in a given Number





 

I have given here Turbo C code to count the number of digits in a given number. It counts the digits using division operation in do while loop. The alternate way to count the number of digits is using log (base 10) operation.

 


Source Code


#include <stdio.h>

#include <conio.h>

#include <math.h>

 

int CountNumberOfDigits_usingLog(int n)

{

   return (int) (log10((double)n) + 1);

}

 

int CountNumberOfDigits(int n)

{

   int numdgits = 0;

   do

   {

      n = n / 10;

      numdgits++;

   } while(n > 0);

   return numdgits;

}

 

void main()

{

    int i, n, number, numdigits, result;   

 

    printf("\nProgram to find the reverse of a number. Enter -1 to exit");

    while(1)

    {

        printf("\nEnter a number: ");

        scanf("%d", &number);

 

        if(number < 0)

            break;

        n = number;

 

        numdigits = CountNumberOfDigits(number);

       

        printf("\nNumber of digits in %d is: %d\n", number, numdigits);

        result = 0;

        for(i = 0; i < numdigits; i++)

        {

            result *= 10;

            result += n % 10;

            n = n / 10;

        }

 

        printf("The reverse of number %d is : %d\n", number, result);

    }

}

Output