Recursion(Fibonacci series)
In this tutorial another example of Recursion. You can see the detailed view of recursion in this post, where we discussed calculating the factorial of a number with recursion. Fibonacci series is a sequence of Fibonacci numbers like,
1,1,2,3,5,8,13,21,34,55,89,144,...
We can define this series in mathematical terms by the following expression,
We can summarise a recursive method to calculate the Fibonacci number for given value n as,
Calculating Fibonacci number is very easy, we can see in the following figure,
Example
Output:
0 1 1 2 3 5 8 13 21 34 55
Video Tutorial
In this tutorial another example of Recursion. You can see the detailed view of recursion in this post, where we discussed calculating the factorial of a number with recursion. Fibonacci series is a sequence of Fibonacci numbers like,
1,1,2,3,5,8,13,21,34,55,89,144,...
We can define this series in mathematical terms by the following expression,
We can summarise a recursive method to calculate the Fibonacci number for given value n as,
Calculating Fibonacci number is very easy, we can see in the following figure,
Example
public
class
DemoRecursion {// Calculate Fibonacci by recursion
public
static
void
main(String[] args) {
DemoRecursion
d=new DemoRecursion();
//to print series
for(int
i=0;i<11;i++)
{
System.out.print(d.fibonacci(i)+"\t");
}
//System.out.println(d.fibonacci(9));
}
int
fibonacci(int num)// Fibonacci
recursive method
{
if(num==0)
{
return
0;
}
else
if(num==1)
{
return
1;
}
else
{
return
fibonacci(num-2)+fibonacci(num-1);
}
}
}
//***********************************************/Output:
0 1 1 2 3 5 8 13 21 34 55
Video Tutorial