Calculate Factorial with recursive function - CSharp Data Structure Algorithm

CSharp examples for Data Structure Algorithm:Factorial

Description

Calculate Factorial with recursive function

Demo Code

using static System.Console;
class Program/*from w w  w.ja  va2s.  c  o m*/
{
   static int Factorial(int number)
   {
      if (number < 1)
      {
         return 0;
      }
      else if (number == 1)
      {
         return 1;
      }
      else
      {
         return number * Factorial(number - 1);
      }
   }
   static void Main(string[] args)
   {
      Write("Enter a number: ");
      if (int.TryParse(ReadLine(), out int number))
      {
         WriteLine(
         $"{number:N0}! = {Factorial(number):N0}");
      }
      else
      {
         WriteLine("You did not enter a valid number!");
      }
   }
}

Result


Related Tutorials