W
warrenbbs
Hi
I've seen in many places the following code (or similar) to display
the nth number in the fibonacci sequence via recursion:
public class fibonacci
{
static int fib(int n)
{
if (n==0||n==1) return 1;
else {
return fib(n-1)+fib(n-2);
}
}
public static void main(String[] args)
{
System.out.print(fib(Integer.parseInt(args[0])));
}
}
It's obviously a basic piece of code, but what I'm struggling to
understand is exactly HOW it returns the correct number. I guess this
is the key line:
return fib(n-1)+fib(n-2);
I understand the underlying principle for determining the correct
number in the sequence and obviously I can see that if the input is 0
or 1 then 1 is returned, but if I enter, say, 6, how does this class
actually return 13? Can anyone show me a step-by-step of what is
happening in the recursive function?
Sorry, I realise this is a lame question, but I'd really like to get
my head round it and I'd be grateful for any insight!
thanks
warren
I've seen in many places the following code (or similar) to display
the nth number in the fibonacci sequence via recursion:
public class fibonacci
{
static int fib(int n)
{
if (n==0||n==1) return 1;
else {
return fib(n-1)+fib(n-2);
}
}
public static void main(String[] args)
{
System.out.print(fib(Integer.parseInt(args[0])));
}
}
It's obviously a basic piece of code, but what I'm struggling to
understand is exactly HOW it returns the correct number. I guess this
is the key line:
return fib(n-1)+fib(n-2);
I understand the underlying principle for determining the correct
number in the sequence and obviously I can see that if the input is 0
or 1 then 1 is returned, but if I enter, say, 6, how does this class
actually return 13? Can anyone show me a step-by-step of what is
happening in the recursive function?
Sorry, I realise this is a lame question, but I'd really like to get
my head round it and I'd be grateful for any insight!
thanks
warren