Fibonacci numbers (Visual Basic .NET)

From LiteratePrograms

Jump to: navigation, search
Other implementations: ALGOL 68 | Alice ML | bc | C | C Plus Plus templates | dc | E | Eiffel | Erlang | Forth | FORTRAN | Haskell | Hume | Icon | Java | JavaScript | Lisp | Logo | Lua | Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | Smalltalk | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by

1 \\ \end{cases} ."/>

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.


In this article we show how to calculate Fibonacci numbers in Visual Basic .NET.

Implementation

This is a very simple recursive implementation, which will become slow on big numbers, because the numbers are recalculated for each recursion.

<<fib>>=
    Function fib(ByVal n)
        If n < 2 Then Return n Else Return fib(n - 1) + fib(n - 2)
    End Function

Test

This simple test program will print the first 30 Fibonacci numbers on the console.

It can be compiled from within "Microsoft Visual Studio .NET", or with the VBC.EXE compiler.

<<fibonacci.vb>>=
Imports System.Console
Module Fibonacci
fib
    Sub Main()
        Dim n As Integer
        For n = 1 To 30
            WriteLine(n & ":" & fib(n))
        Next
    End Sub
End Module
Download code
Views