Well, isn't that what happens when you call the function with values of 0, 1, 2, 3, 4, 5, ...
(Did you try it?)
OK! I'm with you so far.
No. According to the code, for k = 1, since that is less than 2, the function returns the value of its argument (returns 1).
Not true. When you call a function (recursively or not) with an int argument, changes the function makes internally with the parameter do not cause changes of the argument back in the calling function. That's fundamental. The calling function is not "sending it k to work with," it is sending it the
value of k. The function works on its own copy of the parameter.
If you have trouble following the code "in your head," try it with pencil and paper. Step through it for k = 2.
Sometimes it is helpful to make the program tell you what it is working with at each step:
private static int fib(int k)
{
System.out.println("Into fib with k = " + k);
if (k < 2) {
System.out.println(" fib(" + k + ") returning " + k);
return k;
}
System.out.println("In fib(" + k + ") calling fib(" + (k-1) + ")");
int i1 = fib(k-1);
System.out.println(" After calling fib(" + (k-1) + ") return value = " +
i1 + ", k = " + k);
System.out.println("In fib(" + k + ") calling fib(" + (k-2) + ")");
int i2 = fib(k-2);
System.out.println(" After calling fib(" + (k-2) + ") return value = " +
i2 + ", k = " + k);
return i1+i2;
}
If you call this with k = 2, you should see
Into fib with k = 2
In fib(2) calling fib(1)
Into fib with k = 1
fib(1) returning 1
After calling fib(1) return value = 1, k = 2
In fib(2) calling fib(0)
Into fib with k = 0
fib(0) returning 0
After calling fib(0) return value = 0, k = 2
fib(2) = 1
(Note that I separated the two recursive calls so that I could show the results separately. In java, putting the two calls in a single expression gives the same result that I showed as the expression is evaluated left-to-right.
Cheers!
Z