Jamisco Jamisco - 20 days ago 5
C# Question

I just do not understand how this code is able to calculate factorial of the given numbers

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}

static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}


so i know it has to do with the function being a recursion but how is the code able to know when to keep multiplying the integers less than 6 in order to find the factorial. Also how does the code know when to stop multiplying when it reaches 6. If this was in a loop i could fully understand how this would be possible but with no loop i just do not understand.

I'm still in the tutorial of learning c#, if you can please try to keep it as simple as possible.

Any help would be greatly appreciated.

Answer

Let's step through factorial(6).

What's factorial(6)? factorial(5) * 6.

What's factorial(5)? factorial(4) * 5.

What's factorial(4)? factorial(3) * 4.

What's factorial(3)? factorial(2) * 3.

What's factorial(2)? factorial(1) * 2.

What's factorial(1)? 1.

You then just go backward from there and you'll arrive at your answer:

factorial(6) = 1 * 2 * 3 * 4 * 5 * 6.