Venomous Gecko
Venomous Gecko

Reputation: 13

Issue with Recursive Methods ("missing return statement")

so I have a program that is running a bunch of different recursive methods, and I cannot get it to compile/run. The error is in this method, according to my computer:

public static int fibo(int n)
    // returns the nth Fibonacci number
    {
     if (n==0)
     {
      return 0;
     }
     else if (n==1)
     {
       return 1;
     }

     else if (n>1)
     {
      return fibo(n-1) + fibo(n-2);
     }


    }

I have this method called correctly in my main method, so the issue is in this bit of code.

Upvotes: 1

Views: 31

Answers (2)

Annie
Annie

Reputation: 305

I think I can help you in this. Add return n; after your else if. Outside of the code but before the last curlicue.

The code will work as long as n ≥ 0 btw; another poster here is right in that you may want to add something to catch that error.

Upvotes: 1

Tui Popenoe
Tui Popenoe

Reputation: 2114

Make sure all possible paths have a return statement. In your code, if n < 0, there is no return statement, the compiler recognizes this, and throws the error.

public static int fibo(int n)
    // returns the nth Fibonacci number
    {
     if (n<=0)
     {
      return 0;
     }
     else if (n==1)
     {
       return 1;
     }
     else // All other cases, i.e. n >= 1
     {
      return fibo(n-1) + fibo(n-2);
     }
    }

Upvotes: 1

Related Questions