Fibonacci numbers in Basic
Example for versions
Microsoft Visual Basic 6
This example uses recursive definition of Fibonacci numbers.
Option Explicit
Declare Function AllocConsole Lib "kernel32" () As Long
Declare Function FreeConsole Lib "kernel32" () As Long
Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Declare Function GetStdHandle Lib "kernel32" (ByVal nStdHandle As Long) As Long
Declare Function WriteConsole Lib "kernel32" Alias "WriteConsoleA" _
(ByVal hConsoleOutput As Long, lpBuffer As Any, ByVal _
nNumberOfCharsToWrite As Long, lpNumberOfCharsWritten As Long, _
lpReserved As Any) As Long
Declare Function Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) As Long
Public Function Fibonacci(ByVal n As Integer) As Integer
If (n <= 2) Then
Fibonacci = 1
Else
Fibonacci = Fibonacci(n - 1) + Fibonacci(n - 2)
End If
End Function
Private Sub Main()
'create a console instance
AllocConsole
'get handle of console output
Dim hOut As Long
hOut = GetStdHandle(-11&)
'output string to console output
Dim s As String
Dim i As Integer
For i = 1 To 16 Step 1
s = Fibonacci(i) & ", "
WriteConsole hOut, ByVal s, Len(s), vbNull, vbNull
Next i
s = "..." & vbCrLf
WriteConsole hOut, ByVal s, Len(s), vbNull, vbNull
'make a pause to look at the output
Sleep 2000
'close the handle and destroy the console
CloseHandle hOut
FreeConsole
End Sub
Comments
]]>blog comments powered by Disqus
]]>