Software & Finance





C# Count Number of Digits in a given Number





 

I have given here 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


using System;

using System.Collections.Generic;

using System.Text;

 

namespace ReverseNumber

{

   class ReverseNumber

   {

      static int CountNumberOfDigits_UsingLog(int number)

      {

         return (int)(Math.Log10((double)number) + 1);

      }

 

      static int CountNumberOfDigits(int number)

      {

         int numdgits = 0;

         do

         {

            number = number / 10;

            numdgits++;

         } while (number > 0);

         return numdgits;

      }

 

      static void Main(string[] args)

      {

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

         while (true)

         {

            System.Console.Write("Enter a Number (-1 to exit): ");

            string input = System.Console.ReadLine();

            int n = 0;

            try

            {

               n = Convert.ToInt32(input);

            }

            catch (System.Exception ex)

            {

               System.Console.WriteLine("Error in the input format\n\n");

               continue;

            }

 

            if (n < 0)

               break;

            int number = n;

 

            int numdigits = CountNumberOfDigits(number);

 

            System.Console.WriteLine("\nNumber of digits in " + number.ToString() + "is : " + numdigits.ToString());

            int result = 0;

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

            {

               result *= 10;

               result += n % 10;

               n = n / 10;

            }

            System.Console.WriteLine("\nThe reverse of number " + number.ToString() + "is : " + result.ToString());

         }

      }

   }

}

Output