w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Count the number of digits in a number

Secondary Nav

C# Sharp Recursion : Exercise-5 with Solution

Write a program in C# Sharp to count the number of digits in a number using recursion.
Test Data :
Input any number : 12345
Expected Output
:
The number 12345 contains number of digits : 5

C# Sharp Code:

using System;

class RecExercise5
    {
        static void Main(string[] args)
        {
            
        Console.Write("\n\n Recursion : Count the number of digits in a number :\n");
        Console.Write("---------------------------------------------------------\n");
        Console.Write(" Input any number : ");
        int num = Convert.ToInt32(Console.ReadLine());           
        Console.Write("\n The number {0} contains number of digits : {1} ",num,getDigits(num, 0));
        Console.ReadLine();
        }

public static int getDigits(int n1, int nodigits)
    {
    if (n1 == 0)
        return nodigits;

    return getDigits(n1 / 10, ++nodigits);
    }
}

C# Sharp Practice online:


using System;

class RecExercise5
    {
        static void Main(string[] args)
        {
            
        Console.Write("\n\n Recursion : Count the number of digits in a number :\n");
        Console.Write("---------------------------------------------------------\n");
        Console.Write(" Input any number : ");
        int num = Convert.ToInt32(Console.ReadLine());           
        Console.Write("\n The number {0} contains number of digits : {1} ",num,getDigits(num, 0));
        Console.ReadLine();
        }

public static int getDigits(int n1, int nodigits)
    {
    if (n1 == 0)
        return nodigits;

    return getDigits(n1 / 10, ++nodigits);
    }
}

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.