Given the following recursive function:
// Pre-condition: y is non-negative.
int mysterious(int x, int y) {
if (y == 0) return x;
return 2*mysterious(x, y-1);
}
What is the return value of mysterious(3, 2)?
Here is my call stack:
return 2*mysterious(3, 2-1) => 2*3 => 6, 2*1 => mysterious(6,2)
return 2*mysterious(6, 2-1) => 6*2 => 12, 2*2 => mysterious(12, 2)
But it seems like y will never reach 0. What am I doing wrong?
A recursive function is a function that calls itself during its execution. The process may repeat several times, outputting the result and the end of each iteration.
A classic example of recursion The classic example of recursive programming involves computing factorials. The factorial of a number is computed as that number times all of the numbers below it up to and including 1. For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .
A recursive formula refers to a formula that defines each term of a sequence using the preceding term(s). The recursive formulas define the following parameters: The first term of the sequence. The pattern rule to get any term from its previous term.
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.
mysterious(3, 2) = 2 * mysterious(3, 1) = 2 * 2 * mysterious(3, 0) = 2 * 2 * 3 = 12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With