Fibonacci sequence. The Fibonacci sequence has many uses. In this sequence, each number is the sum of the previous two numbers.
In the 1200s Fibonacci published the sequence, showing its use in collecting interest. The sequence has been shown to have many other uses.
Example. This is an iterative implementation of the Fibonacci sequence, where we compute numbers in a loop. We use a temporary variable to copy the previous number.
Tip The Fibonacci method returns a number within the Fibonacci sequence, by its index.
However You could store all the numbers in a List for better lookup performance. This eliminates the entire loop after initialization.
Note The output matches the Fibonacci sequence. And we can add the two previous numbers up to check the sequence mentally.
Module Module1
Function Fibonacci(ByVal n As Integer) As Integer
Dim a As Integer = 0
Dim b As Integer = 1
' Add up numbers.
For i As Integer = 0 To n - 1
Dim temp As Integer = a
a = b
b = temp + b
Next
Return a
End Function
Sub Main()
' Display first 10 Fibonacci numbers.
For i As Integer = 0 To 10
Console.WriteLine(Fibonacci(i))
Next
End Sub
End Module0
1
1
2
3
5
8
13
21
34
55
Function notes. We use a Function, not a Sub, because a return value is required. If we cached the values in a list (a lookup table) this would be faster.
Version 2 Functional code uses method calls. A recursive method calls itself, so we define a method in terms of itself.
A recursive method can be used to compute Fibonacci numbers: each value is defined as the sum of the previous two. But an iterative solution is often easier to read and understand.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 19, 2025 (image).