Nature contains many patterns. Fibonacci numbers are a fascinating sequence. This sequence models and predicts financial markets and natural phenomena.
We can compute Fibonacci numbers in C# code with recursion. This approach can be slow. It is also possible to use iteration.
To begin, we should review the sequence of numbers itself. When we design our program, we can test against these values.
Numbers: 0, 1, 1, 2, 3, 5, 8, 13...
This is an iterative method. Conceptually, an iterative Fibonacci method stores the result of the previous Fibonacci number before computing the next one.
Fibonacci()
to simply use Console.WriteLine
.using System; class Program { public static int Fibonacci(int n) { int a = 0; int b = 1; // In N steps, compute Fibonacci sequence iteratively. for (int i = 0; i < n; i++) { int temp = a; a = b; b = temp + b; } return a; } static void Main() { for (int i = 0; i < 15; i++) { Console.WriteLine(Fibonacci(i)); } } }0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
One problem with this implementation is that the int
types will overflow past the 47th Fibonacci number. It cannot be used on large numbers.
Fibonacci()
to return double
. Also change a, b, and temp to be of type double
.The Fibonacci sequence begins with zero. Fibonacci himself, in 1202, began it with 1, but modern scientists just use his name, not his version of the sequence.
Fibonacci numbers are a useful pattern. But they also teach us about programming. By storing the previous value in a local variable, we avoid computational work.