Factorial in Basic

Example for versions Microsoft Visual Basic 6

This example uses iterative factorial definition. Trying to calculate 13! produces an arithmetic overflow error, so program output ends with line “12! = 479001600”. After this a message “Run-time error ‘6’: Overflow” pops up.

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

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
    Dim f As Long
    f = 1
    s = "0! = 1" & vbCrLf
    WriteConsole hOut, ByVal s, Len(s), vbNull, vbNull
    For i = 1 To 16 Step 1
        f = f * i
        s = i & "! = " & f & vbCrLf
        WriteConsole hOut, ByVal s, Len(s), vbNull, vbNull
    Next i
    'make a pause to look at the output
    Sleep 2000
    'close the handle and destroy the console
    CloseHandle hOut
    FreeConsole
End Sub