0
Recursion Function Questions
Three questions: (1) Why does print(n) return 3,2,1,0,1 and with final output 2? (2) Isn't "n < 2 ? n : (fib(n: n-1) + fib(n: n-2))" a ternary conditional statement? (i.e. TRUE/FALSE) Also, "(fib(n: n-1) + fib(n: n-2))" appears to always output 3 (3-1 + 3-2 = 3). (3) If n = 1 and then 0 at some point, why doesn't the ternary conditional end with 1? Here is the code: func fib(n: Int) -> Int { print(n) return n < 2 ? n : (fib(n: n-1) + fib(n: n-2)) } print(fib(n: 3)) // returns 3,2,1,0,1 for n; printing of function output = 2
5 Answers
+ 1
Here is the structure of fib():
(1)-return 1
/
(3) (0)-return 0
\ /
(2)
\
(1)-return 1
fib(n: 3)
-> fib(n: 2) + fib(n: 1)
-> fib(n: 1) + fib(n: 0) + fib(n: 1)
-> 1 + 0 + 1 = 2
Why the output goes 32101 is because the left operand should be done processing before the right one, which is fib(n: 2). You see why I don't change fib(n: 1) at the second step. It's because the function haven't process it.
And yes, it's ternary operator.
+ 1
Please post code then we can check much better what your doubts
+ 1
Thank you. I finally understand. The diagram above did help.
/* Explanation:
fib function with n-1 shown as ()*
fib function with n-2 shown as ()
print fib(3)
| \
| (1)[RETURNS 1]
|
(2)*
| \
| (0)[RETURNS 0]
|
(1)*[RETURNS 1]
RETURNS TOTAL = 2
*/
0
Thank you.
So the ternary operator doesn't stop the function even though n <2?
Output of print(n) is 3, then 2, then 1, then 0, then 1. You would think that the ternary operator would stop the function when n=1, because n <2.
Here is the code again.
func fib(n: Int) -> Int {
print(n)
return n < 2 ? n : (fib(n: n-1) + fib(n: n-2))
}
print(fib(n: 3))
// returns 3,2,1,0,1 for n; printing of function output = 2
0
Doug Myer the function does stop and return n when n< 2