Anytime you want to write a recursive function in any language think about two things:
1) Base case (could be base cases)
2) Recurrence relation.
You in your question have both of these. Your base cases are:
f(0) = 0 & f(1) = 1
Your recurrence relation is:
f(n) = f(n-1) + f(n-2)
Now, let's construct our recursive function. Here are the steps:
1) Name your function & figure out the return type & the input parameters.
public static int fibonacci(int n)
{
}
2) Write your base cases as if-else statements
if(n == 0)
return 0;
else if(n == 1)
return 1;
3) Write your recurrence relation as a recursive call to your function as follows:
return fibonacci(n-1) + fibonacci(n-2);
4) Add any other conditions you want to the top of your function. In your case you want to return 0 if n < 0 (negative). Here is how you do that:
if (n < 0)
return 0;
Now, let's write the complete function:
public static int fibonacci(int n)
{
if (n < 0)
return 0;
else if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
}
I hope this helps you understand how to write recursive functions yourself in the future. Good luck!!