Monday 21 January 2013

Fibonacci Levels

#include<stdio.h>

/*Print the levels of fibonacci recursion and also returns the fibonacci value*/
int fib(int n,int level)
{
    int i;

    for(i=0;i<4*level;i++)  //a*level adjusts the horizontal space between two levels
        printf(" ");

    printf("fib(%d)\n",n);

    if(n==0)
        return 0;

    else if(n==1)
        return 1;

    else 
        return (fib(n-1,++level))+(fib(n-2,level));    //fib(n) = fib(n-1)+fib(n-2) ; n>=2
}

//main function
int main()
{
    int n , f;
   
    printf ("Enter the no. whose fibonacci no. is to be found;  ");
    scanf("%d",&n);
    
    printf("fib(%d)=%d\n", n , fib(n , 0) );
 
   return 0;
}

No comments:

Post a Comment