Hi all
Could someone please explain this program to me, especially lines 25 and 30. I understand that line 30 is a for loop and I understand how it works. However, I am unclear why it is minusing 3 from n and is n the variable passed from line 14? Line 25, I believe, consists of variables and I understand that they are defined by line 7. However, I am unsure how their values change during the running of the program. I would apprciate any help. Thank you.
Listing 7.15. Solving the nth Fibonacci numberusing iteration.
// Listing 7.15
// Demonstrates solving the nth
// Fibonacci number using iteration
#include <iostream.h>
typedef unsigned long int ULONG;
ULONG fib(ULONG position);
int main()
{
ULONG answer, position;
cout << "Which position? ";
cin >> position;
cout << "\n";
answer = fib(position);
cout << answer << " is the ";
cout << position << "th Fibonacci number.\n";
return 0;
}
ULONG fib(ULONG n)
{
ULONG minusTwo=1, minusOne=1, answer=2;
if (n < 3)
return 1;
for (n -= 3; n; n--)
{
minusTwo = minusOne;
minusOne = answer;
answer = minusOne + minusTwo;
}
return answer;
}