C# program to find factorial of a number using recursion
Here's a C# program that finds the factorial of a number using recursion:
using System;
class Program
{
static void Main()
{
int number = 5;
long factorial = CalculateFactorial(number);
Console.WriteLine("Factorial of " + number + " is: " + factorial);
}
static long CalculateFactorial(int number)
{
// Base case: factorial of 0 or 1 is 1
if (number == 0 || number == 1)
{
return 1;
}
else
{
// Recursive case: factorial of number is number multiplied by factorial of (number - 1)
return number * CalculateFactorial(number - 1);
}
}
}
In this program, we have the CalculateFactorial method that takes an integer number as input and returns the factorial of that number.
We have a base case where if the number is 0 or 1, we return 1, as the factorial of 0 or 1 is 1.
In the recursive case, we calculate the factorial of number by multiplying number with the factorial of (number - 1). We make a recursive call to CalculateFactorial with the value (number - 1).
The recursive calls continue until we reach the base case (number equals 0 or 1), at which point the recursion stops and the factorial value is calculated.
In the example above, the output would be:
Factorial of 5 is: 120
The factorial of 5 is calculated as 5 * 4 * 3 * 2 * 1, which equals 120.