-2

I am confused as to how Java is running this specific code. I am comfortable with the Fibonacci sequence but not exactly with how to grapple my mind to the way this specific method is running. So obviously I'm returning 0 if n is 0 and returning 1 if n is 1. Now let us say I pass 3 for n. We return fib(2) + fib(1). How does it know what fib(2) is if it never calculated that in the first place? Does it go through the whole function again to find out what fib(2) is? When does it stop? My mind is going to blow up.

 public static int fib(int n){
    if (n == 0){
        return 0;
    }
    else if (n == 1){
        return 1;
    }
    return (fib(n-1) + fib(n-2));

}
Malte Hartwig
  • 4,477
  • 2
  • 14
  • 30
  • This function calls itself. Lots. – Dawood ibn Kareem Dec 20 '17 at 20:40
  • "_Does it go through the whole function again to find out what fib(2) is?_" Yes, that is what recursion is. "_When does it stop?_" When the condition that does not call the method itself is met - in this case that is when `n == 0 || n == 1`. – takendarkk Dec 20 '17 at 20:42
  • I strongly recommend you have a look at the answers to the duplicate question. Especially chro's answer, which is the best answer in my opinion, but is currently the second highest voted one on the page. – Dawood ibn Kareem Dec 20 '17 at 21:30

1 Answers1

0

You are expreiencing one of the coolest concepts in programming/math called Recursion. It can be beautiful but itcan also be a curse. At the beginning of learning recursive functions I was also driven mad by these compilcated self calling monsters but after a while I recognised how many problems can be solved much easier with recursion. So back to your problem.

So according to Wikipedia the Fibonacci sequence is

"The sequence Fn of Fibonacci numbers is defined by the recurrence relation:

F n = F n−1 + F n−2

n being the current number.

So at the beginning we callfor example

fib(3);

in the method it calls

fib(2);

then in fib(2) it calls

fib(1)

this returns 1 (because of the if) so this gets to fib(2) and fib 2 calls fib(0) results in 0 so fib(2) returns 1

Because fib(3) was interrupted by the other methods its still at the point of returning. which looks like that currently.

return 1 + fib(3 - 2)

fib(1) returns 1 so

fib returns 2 at the end

This was a bit hard to explain but I think you'll understand pretty soon.

TIP: When you cant understand how something executes use a debugger.It helps so much with visualizing data and algorithms. It helps you understand much quicker. fib(1)

Lucas Engleder
  • 661
  • 1
  • 6
  • 18
  • Perfect explanation, thank you so much... Wrote the code on paper and it was much more clear than trying to do it in my head. Happy holidays. – Esteban Barajas Dec 20 '17 at 21:07