Basic
- Appeared in:
- 1964
- Influenced by:
- Influenced:
- Paradigm:
- Typing discipline:
- File extensions:
- .bas
- Versions and implementations (Collapse all | Expand all):
BASIC (“Beginner’s All-purpose Symbolic Instruction Code”) is a family of high-level programming languages.
The first language of the family, Dartmouth Basic was created in 1964. Its purpose was to facilitate teaching computer science and using computers for research purposes for people without special background. Its main design principle was to be simple enough for beginners (in particular, to require no hardware or operating system understanding) and advanced enough for professionals (in particular, to be general-purpose). Its authors put a lot of effort in its promotion, so it became rather widespread and spawned a lot of implementations.
Since Basic is not a single language but a family of languages which vary a lot, the paradigms supported by the languages of the family vary just as much. Thus, early Basic implementations (the original Dartmouth Basic and its contemporaries) allowed only non-structured programming. Years later new dialects introduced means for structured and procedural programming, which were quickly becoming generally adopted paradigms. Finally, Microsoft Visual Basic along with its successor Microsoft Visual Basic .NET and scripting language VBA support object-oriented and event-driven programming and bear little resemblance to their ancestor. The only thing which unites all Basic dialects is their syntax, though even it has changed quite a lot since first implementation.
Basic has two major official standards — “Minimal Basic” (ANSI X3.60-1978 and ISO/IEC 6373:1984) and “Full Basic” (ANSI X3.113-1987 and INCITS/ISO/IEC 10279-1991 (R2005)).
Early Basic dialects have died out long ago, but modern dialects of the family (mainly Visual Basic and VB.NET) retain traditional popularity of the language.
Elements of syntax:
Inline comments | REM (original Basic), ' (Visual Basic) |
---|---|
Case-sensitivity | no |
Variable assignment | varname = value |
Variable declaration | Dim varname As type |
Variable declaration with assignment | Dim varname As type = value |
Deep equality | a = b |
Deep inequality | a <> b |
Comparison | < > <= >= |
Function definition | Sub functionName (argname1 As argtype1, ..., argnameN As argtypeN) ... End Sub |
Function call | functionName(arg1, ..., argN) |
Function call with no parameters | functionName() |
If - then | If condition Then trueBlock End If |
If - then - else | If condition Then trueBlock Else falseBlock End If |
Loop forever | Do While true loopBody Loop |
While condition do | Do While condition loopBody Loop |
Do until condition | Do loopBody Loop Until condition |
For each value in a numeric range, 1 increment | For i = first To last Step 1 loopBody Next i |
Examples:
Hello, World!:
Example for versions Microsoft Visual Basic 6The intended use of Visual Basic is GUI applications development, so creating a simple console application is a non-trivial task itself. This example features:
- importing required functions from standard library;
- console creation;
- getting the handle of console output stream;
- writing the message to this stream and
- deallocation of used objects.
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
s = "Hello, World!" & 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
Factorial:
Example for versions Microsoft Visual Basic 6This 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
Fibonacci numbers:
Example for versions Microsoft Visual Basic 6This 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
Factorial:
Example for versions QBasic 1.1, QuickBASIC 4.5This example uses recursive factorial definition.
The default data type for calculations is floating point, so program output looks like this:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 3.99168Е+07
12! = 4.790016Е+08
13! = 6.227021Е+09
14! = 8.717829Е+10
15! = 1.307674Е+12
16! = 2.092279Е+13
DECLARE FUNCTION factorial (n)
FOR i = 0 TO 16:
PRINT STR$(i) + "! =" + STR$(factorial(i))
NEXT i
END
FUNCTION factorial (n)
IF n = 0 THEN
factorial = 1
ELSE
factorial = n * factorial(n - 1)
END IF
END FUNCTION
Fibonacci numbers:
Example for versions QBasic 1.1, QuickBASIC 4.5Numbers which have already been calculated are stored in array F and are retrieved from it to calculate the next ones. To get program output in required format, the numbers in the array are concatenated to form one string with required delimiters. STR$
function converts a number to a string.
DIM F(16)
F(1) = 1
F(2) = 1
FOR i = 3 TO 16:
F(i) = F(i - 1) + F(i - 2)
NEXT i
DIM S AS STRING
S = ""
FOR i = 1 TO 16:
S = S + STR$(F(i)) + ", "
NEXT i
S = S + "..."
PRINT S
Fibonacci numbers:
Example for versions QBasic 1.1, QuickBASIC 4.5This example uses recursive definition of Fibonacci numbers. Each call of PRINT
function prints the arguments to a separate line and adds a space before and after printed number, so program output looks like this:
1 ,
1 ,
2 ,
3 ,
5 ,
8 ,
13 ,
21 ,
34 ,
55 ,
89 ,
144 ,
233 ,
377 ,
610 ,
987 ,
…
DECLARE FUNCTION fibonacci (n)
FOR i = 1 TO 16:
PRINT fibonacci(i); ", "
NEXT i
PRINT "..."
FUNCTION fibonacci (n)
IF (n <= 2) THEN
fibonacci = 1
ELSE
fibonacci = fibonacci(n - 1) + fibonacci(n - 2)
END IF
END FUNCTION
Fibonacci numbers:
Example for versions QBasic 1.1, QuickBASIC 4.5Fibonacci numbers are calculated using Binet’s formula. The resulting numbers can differ from actual ones slightly due to calculation imprecision; to remove this effect, we use function INT
which truncates fractional part of the number.
DECLARE FUNCTION FIBONACCI (n)
DIM S AS STRING
S = ""
FOR i = 1 TO 16:
S = S + STR$(INT(FIBONACCI(i) + .1)) + ","
NEXT i
S = S + "..."
PRINT S
FUNCTION FIBONACCI (n)
p1 = ((1 + SQR(5)) * .5) ^ n
p2 = ((1 - SQR(5)) * .5) ^ n
FIBONACCI = (p1 - p2) / SQR(5)
END FUNCTION
Factorial:
Example for versions QBasic 1.1, QuickBASIC 4.5This example uses iterative factorial definition. Arithmetic overflow happens when trying to calculate 13!, but different implementations handle it in different ways: QBasic reports an exception, while QuickBasic just proceeds printing negative values.
DIM f AS LONG
f = 1
PRINT " 0 ! ="; f
FOR i = 1 TO 16:
f = f * i:
PRINT i; "! ="; f
NEXT i
END
Hello, World!:
Example for versions QBasic 1.1, QuickBASIC 4.5, bwBASIC 2.50PRINT "Hello, World!"
Hello, World!:
Example for versions Microsoft Visual Basic .NET 9 (2008), vbnc 2.4.2Module Module1
Sub Main()
Console.WriteLine("Hello, World!")
End Sub
End Module
Factorial:
Example for versions Microsoft Visual Basic .NET 9 (2008), vbnc 2.4.2This example uses recursive factorial definition.
Module Module1
Function Factorial(ByVal n As Integer) As Long
If n = 0 Then
Return 1
Else
Return n * Factorial(n - 1)
End If
End Function
Sub Main()
For i As Integer = 0 To 16
Console.WriteLine(i & "! = " & Factorial(i))
Next
End Sub
End Module
Fibonacci numbers:
Example for versions Microsoft Visual Basic .NET 9 (2008), vbnc 2.4.2This example uses recursive definition of Fibonacci numbers.
Module Module1
Function Fibonacci(ByVal n As Integer) As Long
If n < 3 Then
Return 1
Else
Return Fibonacci(n - 1) + Fibonacci(n - 2)
End If
End Function
Sub Main()
For i As Integer = 1 To 16
Console.Write(Fibonacci(i) & ", ")
Next
Console.WriteLine("...")
End Sub
End Module
Quadratic equation:
Example for versions Microsoft Visual Basic .NET 9 (2008), vbnc 2.4.2Module Module1
Sub Main()
Dim A, B, C, D As Integer
Dim p1, p2 As Double
Try
Console.Write("A = ")
A = Val(Console.ReadLine())
Console.Write("B = ")
B = Val(Console.ReadLine())
Console.Write("C = ")
C = Val(Console.ReadLine())
Catch ex As Exception
Console.WriteLine("Invalid input.")
Return
End Try
If A = 0 Then
Console.WriteLine("Not a quadratic equation.")
Return
End If
D = B * B - 4 * A * C
p1 = -B / 2.0 / A
p2 = Math.Sqrt(Math.Abs(D)) / 2.0 / A
If D = 0 Then
Console.Write("x = " & p1.ToString())
ElseIf D > 0 Then
Console.WriteLine("x1 = " & (p1 + p2).ToString())
Console.WriteLine("x2 = " & (p1 - p2).ToString())
Else
Console.WriteLine("x1 = (" & p1.ToString() & "," & p2.ToString() & ")")
Console.WriteLine("x2 = (" & p1.ToString() & ",-" & p2.ToString() & ")")
End If
End Sub
End Module
Quadratic equation:
Example for versions QuickBASIC 4.5PRINT "A = "
INPUT A
IF (A = 0) THEN
PRINT "Not a quadratic equation."
ELSE
PRINT "B = "
INPUT B
PRINT "C = "
INPUT C
D = B * B - 4 * A * C
IF (D = 0) THEN
PRINT "x = " + STR$(-B / 2! / A)
ELSE
IF (D > 0) THEN
PRINT "x1 = " + STR$((-B + SQR(D)) / 2! / A)
PRINT "x2 = " + STR$((-B - SQR(D)) / 2! / A)
ELSE
PRINT "x1 = (" + STR$(-B / 2! / A) + "," + STR$(SQR(-D) / 2! / A) + ")"
PRINT "x2 = (" + STR$(-B / 2! / A) + "," + STR$(-SQR(-D) / 2! / A) + ")"
END IF
END IF
END IF
CamelCase:
Example for versions vbnc 2.4.2This program checks each letter of the string for being a letter; if it is not, it is replaced with a space. After this the string is converted to proper case (all words are lower case, starting with capital letter), and finally all spaces are removed.
Module Module1
Sub Main()
Dim Text As String
Dim i As Long
Try
Text = LCase(Console.ReadLine())
Catch ex As Exception
Console.WriteLine("Invalid input.")
Return
End Try
For i = 1 To Len(Text) Step 1
If InStr("abcdefghijklmnopqrstuvwxyz", GetChar(Text, i)) = 0 Then
Text = Replace(Text, GetChar(Text, i), " ")
End If
Next
Console.WriteLine(Replace(StrConv(Text, vbProperCase), " ", ""))
End Sub
End Module
Factorial:
Example for versions bwBASIC 2.50Factorials are calculated iteratively. Note the type inference: data type for storing factorial values is not declared explicitly, and yet the larger values are calculated without an overflow error.
f = 1
FOR i = 0 TO 16
PRINT i; "! ="; f
f = f * (i + 1)
NEXT i
Fibonacci numbers:
Example for versions bwBASIC 2.50This example shows iterative calculation of Fibonacci numbers and storing them in an array. Note the explicit array declaration and the string variable S$
— string variables names must end with a $
.
DIM F(16)
F(1) = 1
F(2) = 1
FOR i = 3 TO 16
F(i) = F(i - 1) + F(i - 2)
NEXT i
S$ = ""
FOR i = 1 TO 16
S$ = S$ + STR$(F(i)) + ","
NEXT i
S$ = S$ + " ..."
PRINT S$
Hello, World!:
Example for versions VBScript 5.7, VBScript 5.8The program outputs the message into console, and thus should be executed using cscript.exe
.
WScript.Echo("Hello, World!")
Factorial:
Example for versions VBScript 5.7, VBScript 5.8This example shows iterative factorial calculation. Note that no overflow happens, though the type of factorial variable is inferred from its usage and never set explicitly.
f = 1
For i = 0 To 16
WScript.Echo(i & "! = " & f)
f = f * (i + 1)
Next
Fibonacci numbers:
Example for versions VBScript 5.7, VBScript 5.8This program calculates Fibonacci numbers recursively. Note the absence of a lot of elements typical for other Basic dialects: variable declarations and function return type, explicit number-to-string conversion before concatenation etc.
Function Fibonacci(N)
If N < 2 Then
Fibonacci = N
Else
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function
For i = 1 To 16
res = res & Fibonacci(i) & ", "
Next
WScript.Echo (res & "...")
CamelCase:
Example for versions VBScript 5.7, VBScript 5.8Unlike many other Visual Basic versions, VBScript has no StrConv
function. In the end character-by-character processing of the string turns out to be easier.
Text = LCase(WScript.StdIn.ReadLine)
CamelCase = ""
WasSpace = True
For i = 1 To Len(Text)
Ch = Mid(Text, i, 1)
If InStr("abcdefghijklmnopqrstuvwxyz", Ch) = 0 Then
WasSpace = True
Else
If WasSpace Then
CamelCase = CamelCase & UCase(Ch)
Else
CamelCase = CamelCase & Ch
End If
WasSpace = False
End If
Next
WScript.Echo CamelCase
Quadratic equation:
Example for versions VBScript 5.7, VBScript 5.8Function GetInt()
Input = WScript.StdIn.ReadLine
If not IsNumeric(Input) Then
WScript.Echo "Coefficient is not a number."
WScript.Quit
End If
GetInt = CInt(Input)
End Function
A = GetInt()
If A = 0 Then
WScript.Echo "Not a quadratic equation."
WScript.Quit
End If
B = GetInt()
C = GetInt()
D = B * B - 4 * A * C
p1 = -B / 2.0 / A
p2 = Sqr(Abs(D)) / 2.0 / A
If D = 0 Then
WScript.Echo "x = " & p1
Else
If D > 0 Then
WScript.Echo "x1 = " & (p1 + p2)
WScript.Echo "x2 = " & (p1 - p2)
Else
WScript.Echo "x1 = (" & p1 & ", " & p2 & ")"
WScript.Echo "x2 = (" & p1 & ", " & -p2 & ")"
End If
End If
Comments
]]>blog comments powered by Disqus
]]>