Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Fibonacci series using recursion in C

Fibonacci series is a sequence of following numbers
0 1 1 2 3 5 8 13 21 ....

Code : Compute fibonacci numbers using recursion method


  1. #include<stdio.h>
  2. int Fibonacci(int);
  3. int main()
  4. {
  5. int n, i = 0, c;
  6. scanf("%d",&n);
  7. printf("Fibonacci series\n");
  8. for ( c = 1 ; c <= n ; c++ )
  9. {
  10. printf("%d\n", Fibonacci(i));
  11. i++;
  12. }
  13. return 0;
  14. }
  15. int Fibonacci(int n)
  16. {
  17. if ( n == 0 )
  18. return 0;
  19. else if ( n == 1 )
  20. return 1;
  21. else
  22. return ( Fibonacci(n-1) + Fibonacci(n-2) );
  23. }

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.