Search code examples
c#recursionfactorial

C# using recursion with only one return


I have the following recursive function

public int Factorial(int number_to_calculate)
{
    if (StackChanged != null)
    {
        StackChanged(new CustomEventArgs(StackValue, Result));
    }

    System.Threading.Thread.Sleep(wait_time);
    if (number_to_calculate == 0)
    {
        StackValue--;
        return 1;
    }
    else
    {
        StackValue++;
        Result = (number_to_calculate * Factorial(number_to_calculate - 1));
    }

    if (StackChanged != null)
    {
        StackChanged(new CustomEventArgs(StackValue, Result));
    }
    StackValue--;
    System.Threading.Thread.Sleep(wait_time);
    return Result;
}

Apparently my supervisor is not ok with me having 2 returns, but wants the function to be recursive. So I only need one return. I already tried using an accumulator with goto beginning,in order to have only one return, but i need to increment StackValue every time the function calls itself and decrement it when it comes out of recursion. This way I won't know when it comes out.

Does anyone have any ideas?


Solution

  • Instead of

    if (number_to_calculate == 0)
        {
    
            StackValue--;
    
            return 1;
    
        }...
    

    do

    if (number_to_calculate == 0)
        {
    
           result = 1;
    
        }