Ask Question
18 May, 20:18

The way most recursive functions are written, they seem to be circular at first glance, defining the solution of a problem in terms of the problem itself ("A rose is a rose is a rose"). For example, a recursive function to compute the factorial of n might look like this:

+2
Answers (1)
  1. 18 May, 21:06
    0
    Question Continuation

    int factorial (int n) {

    if (n = = 0)

    return 1;

    else

    return n * factorial (n - 1);

    }

    Provide a brief explanation why this recursive function works.

    Show all steps involved in calculating factorial (3) using the function defined.

    Answer:

    1. Brief explanation why this recursive function works.

    First, the recursive method factorial is defined.

    This is the means through with the machine identifies the method.

    The method is defined as integer, the machine will regard it as integer.

    When the factorial is called from anywhere that has access to it, which in this case is within the factorial class itself. This means you can call it from the main method, or you can call it from the factorial method itself. It's just a function call that, well, happens to call itself.

    2. Steps to calculate factorial (3)

    1 First, 3 is assigned to n.

    2. At line 2, the machine checks if n equals 0

    3. If yes, the machine prints 1

    4. Else; it does the following from bottom to top

    factorial (3):

    return 3*factorial (2);

    return 2*factorial (1):

    return 1;

    Which gives 3 * 2 * 1 = 6

    5. Then it prints 6, which is the result of 3!
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “The way most recursive functions are written, they seem to be circular at first glance, defining the solution of a problem in terms of the ...” in 📘 Engineering if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers