Saturday 4 May 2013

How to print the nth number of a Fibonacci series by recursive method in C programming

#include"stdio.h"
#include"conio.h"
void main()
{
int num;
long fibo(int);
void printFiboSeries(int);
clrscr();
printf("\nEnter number : ");
scanf("%d",&num);
printFiboSeries(num);
getch();
}
long fibo(int n)
{
if(n<=2)
return 1;
return fibo(n-1) + fibo(n-2);
}

void printFiboSeries(int n)
{
if(n<1 br="">return;
printFiboSeries(n-1);
printf("%d ",fibo(n)); // printf is called when all function call of printFiboSeries is popped up from
                                   // the stack
}

Suppose input variable is 5 then the result should be 5

                                                            fibo(5)          
                               fibo(4)                      +                    f ibo(3)
           fibo(3)             +         f ibo(2)      +        fibo(2)        +     fibo(1)
fibo(2)   +   fibo(1)     +              1           +             1            +        1
   1         +       1          +              1           +             1            +        1         =  5

No comments: