Fibonacci series is a sequence of following numbers
0 1 1 2 3 5 8 13 21 ....
Code : Compute fibonacci numbers using recursion method
- #include<stdio.h>
-
- int Fibonacci(int);
-
- int main()
- {
- int n, i = 0, c;
-
- scanf("%d",&n);
-
- printf("Fibonacci series\n");
-
- for ( c = 1 ; c <= n ; c++ )
- {
- printf("%d\n", Fibonacci(i));
- i++;
- }
-
- return 0;
- }
-
- int Fibonacci(int n)
- {
- if ( n == 0 )
- return 0;
- else if ( n == 1 )
- return 1;
- else
- return ( Fibonacci(n-1) + Fibonacci(n-2) );
- }
Input : 5
Output:
Explanation
It adds previous two numbers value to compute the next number value. In this program fibonacci series is calculated using recursion, with seed as 0 and 1. Recursion means a function calling itself, in the below code fibonacci function calls itself with a lesser value several times. An termination condition is very important to recursion function, i.e n == 0 and n == 1 or the recursive call would be infinite leading to stack overflow error.