Adsense 728 * 15

Search

Custom Search

Print Fibonacci Series Using Recursion - C, C++ Program

Write a program to print Fibonacci Series using recursion in C, C++. Given a positive integer n, print fibonacci series using recursion.

In my last post, I have already discussed iterative approach to print Fibonacci series.  Let's first refresh what is Fibonacci series.

Fibonacci Series

In Fibonacci series, first two numbers are 0 and 1, and the remaining numbers are the sum of previous two numbers.

For example - Following are Fibonacci series.

0  1  1  2  3  5  8 ......

You can clearly see first two numbers are 0 and 1 and the rest of the numbers are the sum of previous two numbers.

In this post, We will learn how to print Fibonacci series using recursion concept. So let's understand what is recursion.

C, C++ Interview Question.

What is Recursion ?


In simple words, Recursive function is a function that calls itself. Through recursion, We can write much cleaner and shorter code for complex problems.

In recursion, always declare the base condition(terminating condition) otherwise our code will run infinitely until the program run out of memory.

Recursion vs iteration - Difference between recursion and iteration

C Code to Print Fibonacci Series Using Recursion




#include<stdio.h>


void fibonacci(int n){

  static int first=0, second=1, third;

  if(n > 0){

    third = first + second;

    printf("%d",third);

    first = second;
    second = third; 
 
   /* Function call itself. */

    fibonacci(n-1);

   }

}

  
void main(){

   int num;

   printf("Enter the range of fibonacci series");
   scanf("%d",&num);

   printf("%d %d",0,1);

  /* Frist two numbers (0,1) are printed, 
     so we passed n-2 to fibonacci function. */

   fibonacci(num-2);
}

 

Questions on Recursion for Practice

No comments:

Post a Comment