Understanding Recursion for a complete beginner (Fibonacci Series)
Hey everyone, I hope you are doing well
I need some help understanding recursion, can someone explain to me how the base case of the Fibonacci sequence would occur? What would be the base case and then the recursive case?
11 Replies
do you have a specific algorithm that you're looking at?
I posted the solution but I'd like to get a better understanding on what is really happening here
try running through it by hand, trace what happens when you call Fibonacci(2) for example
Sorry I am very new to coding, what do you mean by trace?
my classes called it a "desk check"
basically run the code by writing out the process on paper
so for Fibonacci(2) you'd go through it like
Fibonacci(2) -> Fibonacci(2 - 1) + Fibonacci(2 - 2)
Fibonacci(2 - 1) -> Fibonacci(1) -> 1
Fibonacci(2 - 2) -> Fibonacci(0) -> 0
Fibonacci(2) -> 1 + 0
Fibonacci(2) = 1
Sure, my teacher has used the example of recursion through a factorial which is understand a bit
What basically happens is that the stack stores the base case as factorial 1 and 0 = 1 then each time you multiply it by 1 more then the factorials below (2 * 1)
the idea is that your fib(2) call makes 2 other fib calls, as such:
it quickly grows a lot more complex 😄
so for
Fib(4)
there are 8 "internal" fib calls
we can easily demonstrate this with the following codePobiega
REPL Result: Success
Console Output
Compile: 453.561ms | Execution: 76.074ms | React with ❌ to remove this embed.