I came up with the following code to work out Fibonacci sequence.
My main question is, why does it return the correct value? If I added a line telling it to return a result when a==1
, I'd understand getting the correct return value, but as it is, I can't work it out.
I'd also like to know if there are any advantages in using the normal recursive algorithm over this one?
int calculate(int a,int result,int old)
{
if (a>0)
{
printf("%d ",result);
return calculate (a-1,result+old,result);
}
}
int main()
{
int number,choice;
printf("To start from 0 enter 0. To start from one enter any other number.\n");
scanf("%d",&choice);
printf ("Choose the number of times you wish to go for.\n");
scanf("%d",&number);
if (choice==0)
{
printf("Result= %d",calculate(number,0,1));
return 0;
}
printf("Result= %d",calculate(number,1,0));
return 0;
}