How did this get 8?

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2010-03-09T18:36:39Z Indexed on 2010/03/15 4:49 UTC
Read the original article Hit count: 229

Filed under:
|
|

Here's the code:

class qual
{
    public static int fibonacci(int n)
    { 
        if (n == 0 || n == 1) 
        { 
            return 1; 
        } 
        else 
        { 
            return fibonacci(n-1) + fibonacci(n-2); 
        } 
    } 

    public static void main(String[] arg) 
    {
        System.out.println(fibonacci(5));
    }
}

The output was 8. The output should be 8 but when I look at this I think it should be 7 ((5-1) +(5-2)).

Why was the output 8? I think the reasoning behind getting 8 will make recursion maybe stop being confusing for me.

© Stack Overflow or respective owner

Related posts about java

Related posts about recursion