java - Recursion - need to sum varibale but its'nt working -


i want sum not reset each time, how possible?

the general idea of code have number of rabbits, each rabbit @ number 3 has 3 ears each time n comes number divisible 3 enters sum 3, otherwise enters sum 2, in recursion.

the code:

public static int rabbit(int n){     int sum=0;     if(n%3==0)     sum+=3;     else if(n%3!=0)         sum+=2;      if(n==0)         return sum;      return rabbit(n-1);  } 

thank's

the problem code not using sum unless n zero.

the return rabbit(n-1); makes recursive call, forgets factor sum result.

you can fix adding sum value return:

return sum + rabbit(n-1);