C++ Bonus Program # 13
K. Dzwonkiewicz
Fibonacci Numbers
Write a test program that calculates the nth Fibonacci number.
The sequence of Fibonacci numbers is defined as follows: the first number is 1, the second number is 1, and each consecutive number is the sum of the previous two. In other words,
F1 = 1;
F2 = 1;
Fn = F(n-1) + F(n-2);
The first few numbers in the sequence are 1, 1, 2, 3, 5, 8, 13, … The numbers are named after Leonardo Pisano (Fibonacci), who invented the sequence in 1202. The numbers have many interesting mathematical properties and even more computer applications.
Your main program should prompt the user for a positive integer n, call the Fibonacci(n) function, and display the result. Note that Fibonacci numbers grow rather quickly, so it is a good idea to keep them in variables of the long or even long double data type and to request small n when you test your program.
The Fibonacci(n) function can be based on one iterative loop. You can have it keep two previously calculated numbers f1 and f2, find the next number f3 = f2 + f1, and then, before the next pas through the loop, shift the values between the variables as follows:
…
f1 = f2;
f2 = f3;
…
“You can’t expect to wield supreme executive power just ‘cause some watery tart through a sword at you.” Peasant (Monty python and the Search for the Holy Grail)
“You can’t have pudding if you don’t eat your meat!” - Floyd