1

I am running this java code and I am getting an error "missing return statement" Please help. I am running using cmd in windows.

public class Fibonocci {

    public static void main(String[] args) {

        int i, limit, c;
        i = 0;
        limit = 5;
        System.out.println("Fibonocci series :");
        for (c = 1; c <= limit; c++) {
            System.out.println(fib(i));
            System.out.println("/n");
            i++;
        }

    }

    public static int fib(int p) {
        if (p == 0) {
            return 0;
        }
        if (p == 1) {
            return 1;
        } else if (p > 1) {
            return (fib(p - 1) + fib(p - 2));
        }
    }
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
Sam
  • 181
  • 2
  • 3
  • 13

2 Answers2

3

You are missing a default return. You are returning from if and else if.

What if both conditions not satisfied ? You need to provide that as well.

I would like to suggest to return -1 id both conditions not satisfied which is for negative numbers negative

public static int fib(int p) {
        if (p == 0)
            return 0;
        else if (p == 1)
            return 1;
        else if (p > 1)
            return (fib(p - 1) + fib(p - 2));
        else
            return -1;
    } 
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

Your code doesn't return anything if p<0.

You can change it to :

  public static int fib(int p){
      if (p<=0) // or perhaps you wish to throw an exception if a negative value is entered
          return 0;
      else if (p==1)
          return 1;
      else // when you end the if statement in else instead of else-if
           // your method is guaranteed to return something for all inputs
          return(fib(p-1)+fib(p-2));
  }
Eran
  • 387,369
  • 54
  • 702
  • 768