I am studying C# on my own and was curious how a simple code runs.
I inserted a linebreak on the if
statement and stepped into it line by line. I want to know why the code keeps coming back to the curly brace above the if
statement when you run the code after the compiler knows the if statement is false? It doesn't return the result from the else statement just yet until the if
statement is true
; and when it does, it goes back and forth into the else statement adding 1 to the num
value to perform the factorial.
Can anyone explain it to me better?
namespace Factorial
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Factorial of six is :" + manipulator.factorial(6));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
}
}
The method is recursive, so it will call itself.
When you call factorial(6)
to calculate 6*5*4*3*2*1
, it will in turn call factorial(5)
to calculate the part 5*4*3*2*1
and multiply that with 6
.
The call to factorial(5)
will in turn call factorial(4)
to calculate 4*3*2*1
and multiply that with 5
.
So it will keep calling itself until the call is factorial(1)
and the first part of the if
statement ends the recursion.
When you single step through the code you will se the execution jump to the start of the method for each call deeper, until you get to the innermost call where it will start returning from all the calls. If you watch the call stack, you will see that it grows with each level of recursion, then shrinks again.