» » » Write a c program to generate fibonacci series using recursion

  • Fibonacci series starts from 0 ,1 and the next number should be sum of previous two numbers.
  • 0+1=1, so the next number in Fibonacci series in c program is 1. 0 1 1 
  • 0 1 1 2 3 5 8.. and so on.
  • We have already seen this c program without using recursion.
  • Now we will see how to generate fibonacci series by using recursion.
  • A function called by itself : recursion. 
  • Fibonacci series c programming using function


Program #1 : Write a C program to print / generate fibonacci series up to n numbers.  Take input from user. By using recursion


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // C program to generate  fibonacci series by using recursion 
  5. //www.instanceofjava.com
  6.  
  7. //Function declaration
  8. long long Printfibonacci(int num);
  9.  
  10.  
  11. int main()
  12. {
  13.     int num;
  14.     long long fibonacci;
  15.      
  16.     //Reads number from user to find nth fibonacci term
  17.     printf("Enter any number to generaye fibonacci series up to ");
  18.     scanf("%d", &num);
  19.      
  20.     printf("%d %d ",0,1);  
  21.     Printfibonacci(num-2);//n-2 numbers. i.e 1 and 2 are printed already
  22.      
  23.     getch();
  24. }
  25.  
  26.  
  27. /**
  28.  
  29.  * Recursive function  
  30. */
  31. long long Printfibonacci(int num) 
  32. {
  33.     static int n1=0,n2=1,n3;  
  34.     if(num>0){  
  35.          n3 = n1 + n2;  
  36.          n1 = n2;  
  37.          n2 = n3;  
  38.          printf("%d ",n3);  
  39.          Printfibonacci(num-1); //Recursively calls Printfibonacci()
  40.     }   
  41. }

Output:


fibonacci recursive c prorgam

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu