Home
Map
Fibonacci SequenceCompute Fibonacci numbers with an iterative algorithm that uses a for-loop.
C#
This page was last reviewed on Sep 7, 2023.
Fibonacci. Nature contains many patterns. Fibonacci numbers are a fascinating sequence. This sequence models and predicts financial markets and natural phenomena.
Computational methods. We can compute Fibonacci numbers in C# code with recursion. This approach can be slow. It is also possible to use iteration.
Input and output. 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...
An example. This is an iterative method. Conceptually, an iterative Fibonacci method stores the result of the previous Fibonacci number before computing the next one.
Note To compute a Fibonacci number at a certain position N, we have to loop through all previous numbers starting at position 0.
Tip If you just want to list Fibonacci numbers, you could change Fibonacci() to simply use Console.WriteLine.
And This would make the method print out each number as it is computed, which would reduce the total amount of computation required.
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
Problem, overflow. One problem with this implementation is that the int types will overflow past the 47th Fibonacci number. It cannot be used on large numbers.
Tip To solve this problem, you can change Fibonacci() to return double. Also change a, b, and temp to be of type double.
int, uint
double
Discussion. 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.
Tip I tested the output of the program and it is correct. I usually try to post correct code.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.