Fibonacci in Java code

public class Fibonacci {
    public static long fib(int n) {
        if (n <= 1) return n;
        else return fib(n-1) + fib(n-2);
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        for (int i = 1; i <= N; i++)
            System.out.println(i + ": " + fib(i));
    }

}

Let’s assume that the user input “java Fibonacci 7”, so the result would be like this: 1: 1

2: 1

3: 2

4: 3

5: 5

6: 8

7: 13

I seem to be totally confused with how this works. Starting with number 3. When the fib(i) method passes 3, shouldn’t it return 3 as well since if n = 3 then the sum of fib(n-1) /which is 2/ and fib(n-2) /which 1/ is 3. And so on the other numbers forward.

Answer

If you pass 3 to your function it will do the following:

fib(3) = fib(2) + fib(1) //so we we are into the else statement, because 3 > 1
= fib(2) + 1             //fib(1) = 1 because 1 <= 1 so you return it (if statement)
= (fib(1) + fib(0)) + 1  //2 > 1 => we go to the else statement
= (1 + 0) + 1            //0 <= 1 & 1 <= 1 so we are into the if and return the values 
= 2

Leave a Reply

Your email address will not be published. Required fields are marked *