I am having difficulty understanding why my code is not producing the expected output. I am using Java and am trying to solve a problem from here.
The problem I am trying to solve is as follows:
"Given a number n, find the nth Fibonacci number. The Fibonacci sequence is a series of numbers where the first two numbers are 0 and 1, and each subsequent number is the sum of the previous two numbers.
For example:
PHP Code:
0 = 0
F1 = 1
F2 = F0 + F1 = 1
F3 = F1 + F2 = 2
Given n = 4, the output should be 3.
Here is the code I have written so far:
PHP Code:
public class Fibonacci {
public static int Fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return Fibonacci(n-1) + Fibonacci(n-2);
}
}
public static void main (String[] args) {
int n = 4;
System.out.println(Fibonacci(n));
}
}
However, when I run the code, I get the output 0 instead of 3. I have tried troubleshooting the code, but have not been able to find the issue. Could someone please help me figure out why the code is not producing the expected output?
Thank you.