Search code examples
c#c++loopsrecursionfactorial

Recursive loop (C#)


Can someone please explain it to me? I wrote a function to calculate the factorial of a number like this in C#:

public int factorial(int input)
{
    if (input == 0 || input == 1)
        return 1;
else
{
    int temp = 1;
    for (int i = 1; i <= input; i++)
        temp = temp * i;
    return temp;
    }
}

But I found some C++ code (I don't really know any C++ btw) which finds a factorial using a recursive loop:

int factorial(int number) {
 int temp;
 if(number <= 1) return 1;
 temp = number * factorial(number - 1);
 return temp;
}

Can someone explain to me how it works? Thanks.


Solution

  • Syntactically, the C++ code is identical to the same code written in C#. Don't let the language discrepancy catch you off guard! It actually looks like C to me, given that the variable is declared at the top of the function; that's not strictly necessary in either C++ or C#. I prefer to declare variables the first time I use them, combining the declaration and initialization in one single statement, but that's merely a stylistic preference that doesn't change the function of the code.

    I'll try to explain this by adding comments to each line of the code snippet:

    // Declare a function named "Factorial" that accepts a single integer parameter,
    // and returns an integer value.
    int Factorial(int number)
    {
        // Declare a temporary variable of type integer
        int temp;
    
        // This is a guard clause that returns from the function immediately
        // if the value of the argument is less than or equal to 1.
        // In that case, it simply returns a value of 1.
        // (This is important to prevent the function from recursively calling itself
        // forever, producing an infinite loop!)
        if(number <= 1) return 1;
    
        // Set the value of the temp variable equal to the value of the argument
        // multiplied by a recursive call to the Factorial function
        temp = number * Factorial(number - 1);
    
        // Return the value of the temporary variable
       return temp;
    }
    

    Recursive calls simply mean that the function calls itself from within the same function. This works because the factorial of n is equivalent to the following statement:

    n! = n * (n-1)! 
    

    One great way to understand how code works is to add it to a test project, then single-step through the code using the debugger. Visual Studio has very rich support for this in C# applications. You can watch how the function recursively calls itself, watching each line execute in sequence, and even seeing the values of the variables change as operations are performed on them.