I am learning Java and I have this code from the internet and running it in Eclipse:
public class Fibonacci {
public static void main (String [] args) {
for (int counter = 0; counter <= 3; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
I've tried to understand it but cannot get it. So I run through the code and counter
gets passed in through the fibonacci
method. As counter starts at 0
and this is what gets passed first, then 1
and I understand the method passes back 0
and then 1
.
When it reaches 2: it will return 2-1 + 2-2 = 2
and it does return this.
When it reaches 3: it will return 3-1 + 3-2 = 3
but it does not return 3
it returns 2
.
Please can someone explain to me why as I cannot figure this out?
Thanks