Google Add

Search

C Program to Print Fibonacci Series Using Recursion

Write a c program to print Fibonacci Series using recursion. Given a positive integer n, we have to write a c code to print fibonacci series using recursion. This question is also very important in terms of technical interviews.

In my last post, I have already discussed C program to print fibonacci series using while, do while & for loop.  Let's first understand, 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 -

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. 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 program, Always specify the base condition(terminating condition) otherwise code will run infinitely until the program run out of memory.

Recursion vs iteration - Difference between recursion and iteration

C Program to Print Fibonacci Series Using Recursion


C Program to Print Fibonacci Series Using Recursion


In this program, we take a number of elements to print in a fibonacci series as an input from user. Then our recursive method print fibonacci series upto that number.


#include<stdio.h>


int fibonacci(int n){

  /**
   if number is less than 2,
   In case of 0 and 1
   */
  if(n < 2) {
      return n;
  }

  //Recursive call
  return fibonacci(n-1) + fibonacci(n-2);

}

  
int main(){

   int num;

   printf("Number of terms to print in a Fibonacci series");
   scanf("%d", &num);

   for(int i = 0; i < num; i++) {
       printf(" %d ", fibonacci(i));
   }

    return 0;
}



Output

Number of terms to print in a Fibonacci series 10

0  1  1  2  3  5  8  13  21  34


Another way to write this program using recursion.


#include<stdio.h>


void fibonacci(int n){

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

  //If n is greater than zero   
  if(n > 0){

    third = first + second;

    printf(" %d ",third);

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

    fibonacci(n-1);

   }

}

  
int main(){

   int num;

   printf("Number of terms to print in a 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);

    return 0;
}

 

C program to delete an element from an array

C program to check Armstrong number

C program to check whether a character is vowel or consonant

Questions on Recursion for Practice

1 comment: