If you want to implement a factorial, such as 6*5*4*3*2*1, you may first think of loop traversal. As follows:
class Program
{
static void Main(string[] args)
{
Console. writeline ("enter a number ");
int number = Convert.ToInt32(Console.ReadLine());
double result = JieCheng(number);
The factorial result of console. writeline (number. tostring () + "is:" + result. tostring ());
Console.ReadKey();
}
public static double JieCheng(int number)
{
if (number == 0)
{
return 0;
}
// The initial value must be set to 1.
double result = 1;
for (int i = number; i >= 1; i--)
{
result = result*i;
}
return result;
}
}
However, there is another way to implement the factorial: 6 * (6-1) * (6-2) * (6-3) * (6-4) * (6-5) or 6 * (6-1) * (5-1) * (4-1) * (3-1) * (2-1 ), that is to say, the following number is always obtained by subtracting 1 from the previous number.
When the implementation logic is the same, and the parameters of the internal recursive method can be obtained by the parameters of the external recursive method through a certain algorithm, this is exactly the time when recursion came into being.
public static double JieCheng(int number) { if (number == 0) { return 1; } return number * JieCheng(number - 1); }