C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Fibonacci: WikipediaVB.NET program that generates Fibonacci sequence
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 Module
Output
0
1
1
2
3
5
8
13
21
34
55
Iterative: This style of code involves loops. We step forward through an operation with for-loops and index variables.
For Each, ForRecursive: This style uses method calls. A recursive method calls itself, so we define a method in terms of itself.
Recursion