Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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

C# Sharp Recursion: Exercise-5 with Solution

Write a program in C# Sharp to count the number of digits in a number using recursion.

Pictorial Presentation:

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

Sample Solution:

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);
    }
}

Sample Output:

 Recursion : Count the number of digits in a number :                                                         
---------------------------------------------------------                                                     
 Input any number : 1000                                                                                      
                                                                                                              
 The number 1000 contains number of digits : 4

Flowchart :

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

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a program in C# Sharp to display the individual digits of a given number using recursion.
Next: Write a program in C# Sharp to print even or odd numbers in a given range using recursion.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.