//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?
If you declare the variable
ias having automatic storage durationthen in each recursive call of the function the variable
iis initialized anew by the value1and you have an infinite loop of recursive calls.When you declare the variable
ias having static storage durationthen it is initialized only once before the program starts.
In any case your function is incorrect because even if the variable
iis 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 variableterms.Moreover the Fibonacci series is a fixed series. The user should not specify the variables
aandb. 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
Here is a demonstration program.
The program output is