Write a program in C#.Net to create a recursive function to find the factorial of a given number.

Answer:

using System;

namespace RecursiveFact
{
    class Program
    {
        // Recursive function to find the factorial of a number
        static int Factorial(int n)
        {
            if (n == 0 || n == 1)  // Base case: factorial of 0 or 1 is 1
                return 1;
            else
                return n * Factorial(n - 1);  // Recursive case
        }

        static void Main(string[] args)
        {
            int num;

            // Taking input from the user
            Console.WriteLine("Enter a number: ");
            num = Convert.ToInt32(Console.ReadLine());

            // Calculating the factorial using recursion
            int result = Factorial(num);

            // Displaying the result
            Console.WriteLine("The factorial of given number is: " + result);
            Console.ReadLine();
        }
    }
}
Scroll to Top