Even more annoying than basic functions, tracing recursion aides in understanding code. Make sure you understand basic function tracing before you tackle this.
Back to Recursion
double expo(double N, int pow) { if(pow < 0) return 1 / expo(-N); else if(pow == 0) return 1; else(pow > 0) return N * expo(N, pow-1); }
f(-3, 3) | - | - | I write my first call of -3. |
f(-3, 3) f(3, 3) | 1 / R(3, 3) | - | Trace the code until a return is reached. Now mark in the second column for the return, and the first since a function is called. |
F(-3, 3) F(3, 3) F(3, 2) | 1 / R(3) 3 * R(3, 2) | - | Trace the code until a return is reached, mark in the second, then the first again. |
F(-3, 3) F(3, 3) F(3, 2) F(3, 1) F(3, 0) | 1 / R(3) 3 * R(3, 2) 3 * R(3, 1) 3 * R(3, 0) 1 | - | Now repeat until we get a finite return. In this case it is one. |
F(-3, 3) F(3, 3) F(3, 2) F(3, 1) F(3, 0) | 1 / R(3) 3 * R(3, 2) 3 * R(3, 1) 3 * R(3, 0) 1 | - - - - 1 | Now trace back up the values. First there is one. |
F(-3, 3) F(3, 3) F(3, 2) F(3, 1) F(3, 0) | 1 / R(3) 3 * R(3, 2) 3 * R(3, 1) 3 * R(3, 0) 1 | - - - 3 * 1 = 3 1 | Next there is 3 * f(3,0), which is 3 * 1, which is 3. |
F(-3, 3) F(3, 3) F(3, 2) F(3, 1) F(3, 0) | 1 / R(3) 3 * R(3, 2) 3 * R(3, 1) 3 * R(3, 0) 1 | - - 3 * 3 = 9 3 * 1 = 3 1 | Now 3 * f(3,1) and from the column we have 3 * 3. |
F(-3, 3) F(3, 3) F(3, 2) F(3, 1) F(3, 0) | 1 / R(3) 3 * R(3, 2) 3 * R(3, 1) 3 * R(3, 0) 1 | 1 / 27 = .03703 3 * 9 = 27 3 * 3 = 9 3 * 1 = 3 1 | And so forth... |
Simple, isn't it? Just take you time and be clear with your tracings.
int Fibonacci(int N) { if(N == 0 || N == 1) return 1; else return Fibonacci(N - 1) + Fibonacci(N - 2); }
F(5) | R(4) + R(3) | - | Trace the function as normal, but now it splits. If the N-1 calls are followed the N-2 are already calculated. |
F(5) F(4) F(3) F(2) F(1) F(0) | R(4) + R(3) R(3) + R(2) R(2) + R(1) R(1) + R(0) 1 1 | - | Going down. |
F(5) F(4) F(3) F(2) F(1) F(0) | R(4) + R(3) R(3) + R(2) R(2) + R(1) R(1) + R(0) 1 1 | 5 + 3 = 8 3 + 2 = 5 2 + 1 = 3 1 + 1 = 2 1 1 | Coming back. Remember to use the notes. |
Back to Recursion
Prev -- Back to Portal -- Next