Printing Fibonacci series using Recursion

134 Views Asked by At
//assume (main function)

int fibonacci(int a,int b){

    //int i inifinite loop(why?)
    static int i=1;

    if(i==terms){
        return 0;
    }
    else{
        int c;

        c=a+b;
        a=b;
        b=c;

        printf(" %d ",c);
        i++;

        fibonacci(a,b);

        return 0;
    }
}

If I declare i variable in fibonacci function (definition function) it prints infinite loop of garbage values instead I used static i variable then the code prints Fibonacci series, please explain me how the statics variable works in this code?

1

There are 1 best solutions below

0
Vlad from Moscow On

If you declare the variable i as having automatic storage duration

int fibonacci(int a,int b){

    //int i inifinite loop(why?)
    int i=1;
    //...

then in each recursive call of the function the variable i is initialized anew by the value 1 and you have an infinite loop of recursive calls.

When you declare the variable i as having static storage duration

int fibonacci(int a,int b){

    //int i inifinite loop(why?)
    static int i=1;
    //...

then it is initialized only once before the program starts.

In any case your function is incorrect because even if the variable i is declared as having static storage duration it is not reset to its initial value after recursive function calls. And moreover it is a bad approach when a function depends on a global variable as your function depends on the global variable terms.

Moreover the Fibonacci series is a fixed series. The user should not specify the variables a and b. It should specify for the function the index of the number in the series that he is going to obtain. And the function should return this number instead of returning 0.

For example the function could be defined the following way

unsigned long long int fibonacci( unsigned int n )
{
    return n < 2 ? n : fibonacci( n - 1 ) + fibonacci( n - 2 );
}

Here is a demonstration program.

#include <stdio.h>

unsigned long long int fibonacci( unsigned int n )
{
    return n < 2 ? n : fibonacci( n - 1 ) + fibonacci( n - 2 );
}

int main()
{
    for (unsigned int i = 0; i < 10; i++)
    {
        printf( "%u -> %llu\n", i, fibonacci( i ) );
    }
}

The program output is

0 -> 0
1 -> 1
2 -> 1
3 -> 2
4 -> 3
5 -> 5
6 -> 8
7 -> 13
8 -> 21
9 -> 34