w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Display the individual digits of a given number

Secondary Nav

C# Sharp Recursion : Exercise-4 with Solution

Write a program in C# Sharp to display the individual digits of a given number using recursion.
Test Data :
Input any number : 1234
Expected Output
:
The digits in the number 1234 are : 1 2 3 4

C# Sharp Code:

using System;
public class RecExercise4
{
    static void Main()
    {

    Console.Write("\n\n Recursion : Display the individual digits of a given number :\n");
    Console.Write("------------------------------------------------------------------\n");
    Console.Write(" Input any number : ");
    int num = Convert.ToInt32(Console.ReadLine()); 
    Console.Write(" The digits in the number {0} are : ",num);
    separateDigits(num);
    Console.Write("\n\n");
    }

    static void separateDigits(int n)
    {
        if (n < 10)
        {
            Console.Write("{0}  ", n);
            return;
        }
        separateDigits(n / 10);
        Console.Write(" {0} ", n % 10);
    }
}

C# Sharp Practice online:


using System;
public class RecExercise4
{
    static void Main()
    {

    Console.Write("\n\n Recursion : Display the individual digits of a given number :\n");
    Console.Write("------------------------------------------------------------------\n");
    Console.Write(" Input any number : ");
    int num = Convert.ToInt32(Console.ReadLine()); 
    Console.Write(" The digits in the number {0} are : ",num);
    separateDigits(num);
    Console.Write("\n\n");
    }

    static void separateDigits(int n)
    {
        if (n < 10)
        {
            Console.Write("{0}  ", n);
            return;
        }
        separateDigits(n / 10);
        Console.Write(" {0} ", n % 10);
    }
}

Improve this sample solution and post your code through Disqus



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

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables