Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Function

Tags:

c

recursion

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?

like image 590
kachilous Avatar asked Dec 17 '10 04:12

kachilous


People also ask

What is recursive function and how it works?

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.

What is an example of recursive?

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 .

What is a recursive formula?

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.

What is called recursive?

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.


1 Answers

mysterious(3, 2)

= 2 * mysterious(3, 1)
= 2 * 2 * mysterious(3, 0)
= 2 * 2 * 3
= 12
like image 154
sje397 Avatar answered Nov 12 '22 18:11

sje397