Introduction
BASIC (Beginner’s All-purpose Symbolic Instruction Code) is a family of high-level programming languages designed for ease of use. This cheat sheet covers fundamental syntax elements common to most BASIC dialects, including traditional BASIC, QBasic, Visual Basic, and modern versions like FreeBASIC. While syntax may vary slightly between implementations, these core concepts remain largely consistent.
Program Structure
Program Layout
REM Program begins here
PRINT "Hello, World!"
END ' Program ends here
Line Numbers (Traditional BASIC)
10 PRINT "First line"
20 PRINT "Second line"
30 END
Line Continuation
' Modern BASIC:
PRINT "This is a long line " _
"that continues here"
' Traditional BASIC:
100 PRINT "This is a long line ";
110 PRINT "that continues here"
Multiple Statements on One Line
' Using colon as separator
PRINT "Hello": PRINT "World": END
' With line numbers
10 PRINT "Hello": PRINT "World": END
Data Types
Common Data Types
| Type | Description | Example |
|---|
| INTEGER | Whole numbers | DIM age AS INTEGER |
| SINGLE | Single-precision float | DIM price AS SINGLE |
| DOUBLE | Double-precision float | DIM pi AS DOUBLE |
| STRING | Text | DIM name AS STRING |
| BOOLEAN | True/False | DIM isValid AS BOOLEAN |
Type Declarations
' Variable declaration with type
DIM count AS INTEGER
DIM name AS STRING
DIM price AS DOUBLE
' Type suffix characters (some BASIC variants)
count% = 10 ' Integer (%)
amount! = 19.95 ' Single precision (!)
value# = 123.45 ' Double precision (#)
name$ = "John" ' String ($)
' Multiple declarations
DIM x AS INTEGER, y AS INTEGER, z AS INTEGER
Type Conversion
' String to number
num = VAL("123")
' Number to string
str$ = STR$(123)
' Specific conversions
i% = CINT(3.7) ' Rounds to nearest integer (4)
s! = CSNG(123) ' Convert to single precision
d# = CDBL(123.4) ' Convert to double precision
st$ = CSTR(123) ' Convert to string
Variables & Constants
Variable Names
- Must start with a letter
- Can contain letters, numbers, and some special characters (e.g., underscore)
- Cannot contain spaces or most special characters
- Case-insensitivity in most BASIC dialects (name and NAME are the same)
Variable Declaration
' Implicit declaration (older BASIC)
name$ = "John"
' Explicit declaration (modern BASIC)
DIM name AS STRING
name = "John"
' Array declaration
DIM scores(10) AS INTEGER ' 0-10 (11 elements)
DIM matrix(5, 5) AS DOUBLE ' 2-dimensional array
DIM names$(1 TO 10) AS STRING ' 1-10 range
Constants
' Define a constant
CONST PI = 3.14159
CONST MAX_STUDENTS = 30
' Using a constant
area = PI * radius ^ 2
Operators
Arithmetic Operators
| Operator | Description | Example |
|---|
| + | Addition | a + b |
| – | Subtraction | a – b |
| * | Multiplication | a * b |
| / | Division | a / b |
| \ | Integer Division | a \ b |
| MOD | Modulus | a MOD b |
| ^ | Exponentiation | a ^ b |
Comparison Operators
| Operator | Description | Example |
|---|
| = | Equal to | a = b |
| <> | Not equal to | a <> b |
| < | Less than | a < b |
| > | Greater than | a > b |
| <= | Less than or equal | a <= b |
| >= | Greater than or equal | a >= b |
Logical Operators
| Operator | Description | Example |
|---|
| AND | Logical AND | a AND b |
| OR | Logical OR | a OR b |
| NOT | Logical NOT | NOT a |
| XOR | Exclusive OR | a XOR b |
| EQV | Equivalence | a EQV b |
| IMP | Implication | a IMP b |
String Operators
| Operator | Description | Example |
|---|
| + | Concatenation | “Hello” + “World” |
| & | Concatenation (alternate) | “Hello” & “World” |
Control Structures
Conditional Statements
IF-THEN
' Single line IF
IF age >= 18 THEN PRINT "Adult"
' Multi-line IF
IF score >= 90 THEN
PRINT "Grade: A"
ELSEIF score >= 80 THEN
PRINT "Grade: B"
ELSEIF score >= 70 THEN
PRINT "Grade: C"
ELSE
PRINT "Grade: F"
END IF
SELECT CASE
SELECT CASE day
CASE 1
PRINT "Monday"
CASE 2
PRINT "Tuesday"
CASE 3
PRINT "Wednesday"
CASE 4, 5
PRINT "Thursday or Friday"
CASE 6 TO 7
PRINT "Weekend"
CASE ELSE
PRINT "Invalid day"
END SELECT
Loops
FOR Loop
' Basic FOR loop
FOR i = 1 TO 10
PRINT i
NEXT i
' FOR loop with step
FOR i = 10 TO 1 STEP -1
PRINT i
NEXT i
' Nested FOR loops
FOR i = 1 TO 3
FOR j = 1 TO 3
PRINT i; ","; j
NEXT j
NEXT i
' Early exit
FOR i = 1 TO 100
PRINT i
IF i = 10 THEN EXIT FOR
NEXT i
WHILE Loop
' WHILE loop
count = 1
WHILE count <= 5
PRINT count
count = count + 1
WEND
' DO-WHILE loop
count = 1
DO WHILE count <= 5
PRINT count
count = count + 1
LOOP
DO-UNTIL Loop
' Execute at least once
count = 1
DO
PRINT count
count = count + 1
LOOP UNTIL count > 5
' May not execute if condition already true
count = 1
DO UNTIL count > 5
PRINT count
count = count + 1
LOOP
Infinite Loop with EXIT
DO
INPUT "Enter a number (0 to exit): ", num
IF num = 0 THEN EXIT DO
PRINT "You entered:", num
LOOP
Input and Output
Console Output
' Basic print
PRINT "Hello, World!"
' Print without newline (varies by dialect)
PRINT "Hello, "; ' Semicolon prevents newline
PRINT "World!" ' Output: "Hello, World!"
' Printing variables
name$ = "John"
age = 30
PRINT "Name:", name$, "Age:", age
' Formatting output
PRINT USING "Price: $##.##"; 25.5 ' Output: "Price: $25.50"
PRINT USING "###.##"; 5.25 ' Output: " 5.25"
Console Input
' Input with prompt
INPUT "Enter your name: ", name$
PRINT "Hello, "; name$
' Multiple inputs
INPUT "Enter age and height: ", age, height
PRINT "Age:", age, "Height:", height
' Input without prompt (some dialects)
INPUT age
File I/O
Sequential Files
' Open file for writing
OPEN "data.txt" FOR OUTPUT AS #1
WRITE #1, "Hello", 123, 45.67
CLOSE #1
' Open file for reading
OPEN "data.txt" FOR INPUT AS #1
INPUT #1, text$, num1, num2
CLOSE #1
' Append to file
OPEN "data.txt" FOR APPEND AS #1
WRITE #1, "More data"
CLOSE #1
Random Access Files
' Define record structure
TYPE Person
name AS STRING * 20
age AS INTEGER
END TYPE
' Write to random file
DIM person AS Person
OPEN "people.dat" FOR RANDOM AS #1 LEN = LEN(person)
person.name = "John Smith"
person.age = 30
PUT #1, 1, person
CLOSE #1
' Read from random file
OPEN "people.dat" FOR RANDOM AS #1 LEN = LEN(person)
GET #1, 1, person
PRINT person.name; " is"; person.age
CLOSE #1
Subroutines and Functions
GOSUB Subroutines (Traditional BASIC)
10 PRINT "Main program"
20 GOSUB 100
30 PRINT "Back to main"
40 END
100 PRINT "In subroutine"
110 RETURN
SUB Procedures (Modern BASIC)
' Defining a sub procedure
SUB PrintHeader(title$)
PRINT STRING$(50, "*")
PRINT title$
PRINT STRING$(50, "*")
END SUB
' Calling a sub procedure
PrintHeader("MONTHLY REPORT")
FUNCTION Procedures
' Defining a function
FUNCTION Square(x)
Square = x * x
END FUNCTION
' Using a function
result = Square(5)
PRINT result ' Output: 25
Parameter Passing
' Pass by value (default)
SUB AddOne(x)
x = x + 1 ' Only changes local copy
END SUB
' Pass by reference
SUB AddOne(BYREF x)
x = x + 1 ' Changes original variable
END SUB
Arrays
Array Declaration and Initialization
' Fixed-size array
DIM scores(10) AS INTEGER
' Explicit range
DIM months(1 TO 12) AS STRING
' Multi-dimensional array
DIM matrix(3, 3) AS DOUBLE
' Initialize array elements
FOR i = 0 TO 10
scores(i) = i * 10
NEXT i
' Initialize at declaration (some dialects)
DIM days$(7) = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
Array Operations
' Find array size
DIM values(1 TO 100) AS INTEGER
size = UBOUND(values) - LBOUND(values) + 1 ' 100
' Resize dynamic array (some dialects)
DIM a() AS INTEGER
REDIM a(10)
' Later resize preserving values
REDIM PRESERVE a(20)
Common Built-in Functions
String Functions
| Function | Description | Example |
|---|
| LEN(s$) | String length | LEN(“Hello”) ‘ Returns 5 |
| LEFT$(s$, n) | Leftmost n characters | LEFT$(“Hello”, 2) ‘ “He” |
| RIGHT$(s$, n) | Rightmost n characters | RIGHT$(“Hello”, 2) ‘ “lo” |
| MID$(s$, p, n) | n chars from position p | MID$(“Hello”, 2, 3) ‘ “ell” |
| INSTR(s1$, s2$) | Position of s2$ in s1$ | INSTR(“Hello”, “l”) ‘ 3 |
| UCASE$(s$) | Convert to uppercase | UCASE$(“Hello”) ‘ “HELLO” |
| LCASE$(s$) | Convert to lowercase | LCASE$(“Hello”) ‘ “hello” |
| LTRIM$(s$) | Remove leading spaces | LTRIM$(” Hi”) ‘ “Hi” |
| RTRIM$(s$) | Remove trailing spaces | RTRIM$(“Hi “) ‘ “Hi” |
| TRIM$(s$) | Remove leading and trailing spaces | TRIM$(” Hi “) ‘ “Hi” |
| STR$(n) | Convert number to string | STR$(123) ‘ “123” |
| VAL(s$) | Convert string to number | VAL(“123”) ‘ 123 |
| CHR$(n) | Character with ASCII code n | CHR$(65) ‘ “A” |
| ASC(s$) | ASCII code of first character | ASC(“A”) ‘ 65 |
| STRING$(n, c) | String of n characters c | STRING$(5, “*”) ‘ “*****” |
Math Functions
| Function | Description | Example |
|---|
| ABS(n) | Absolute value | ABS(-5) ‘ 5 |
| INT(n) | Integer part (truncate) | INT(5.7) ‘ 5 |
| FIX(n) | Integer part (toward zero) | FIX(-5.7) ‘ -5 |
| SQR(n) | Square root | SQR(16) ‘ 4 |
| SIN(n) | Sine | SIN(0) ‘ 0 |
| COS(n) | Cosine | COS(0) ‘ 1 |
| TAN(n) | Tangent | TAN(0) ‘ 0 |
| ATN(n) | Arctangent | ATN(1) ‘ 0.7853981… |
| LOG(n) | Natural logarithm | LOG(2.718) ‘ 1 |
| EXP(n) | Exponential (e^n) | EXP(1) ‘ 2.718… |
| RND | Random number between 0 and 1 | RND ‘ 0.7533…(random) |
| SGN(n) | Sign (-1, 0, or 1) | SGN(-5) ‘ -1 |
| CINT(n) | Round to nearest integer | CINT(5.5) ‘ 6 |
| CSNG(n) | Convert to single precision | CSNG(5) ‘ 5.0 |
| CDBL(n) | Convert to double precision | CDBL(5) ‘ 5.0 |
Date/Time Functions
| Function | Description | Example |
|---|
| DATE$ | Current system date | PRINT DATE$ ‘ “01-01-2023” |
| TIME$ | Current system time | PRINT TIME$ ‘ “13:45:30” |
| TIMER | Seconds since midnight | TIMER ‘ 49530.75 |
| YEAR(d) | Year from date | YEAR(“01/01/2023”) ‘ 2023 |
| MONTH(d) | Month from date | MONTH(“01/01/2023”) ‘ 1 |
| DAY(d) | Day from date | DAY(“01/01/2023”) ‘ 1 |
| HOUR(t) | Hour from time | HOUR(“13:45:30”) ‘ 13 |
| MINUTE(t) | Minute from time | MINUTE(“13:45:30”) ‘ 45 |
| SECOND(t) | Second from time | SECOND(“13:45:30”) ‘ 30 |
Error Handling
Basic Error Handling
' ON ERROR statement
ON ERROR GOTO ErrorHandler
' Main program
PRINT "Starting program"
OPEN "nonexistent.txt" FOR INPUT AS #1
PRINT "This line won't execute if the file doesn't exist"
END
' Error handler
ErrorHandler:
PRINT "Error #"; ERR; " occurred"
PRINT "Error description: "; ERROR$(ERR)
RESUME Next
Error Handling Options
' Resume options
ON ERROR GOTO ErrorHandler
' Main code here
x = 10 / 0 ' Error!
ErrorHandler:
PRINT "Error #"; ERR; " at line"; ERL
SELECT CASE ERR
CASE 11
PRINT "Division by zero error"
x = 0 ' Fix the error
RESUME NEXT ' Continue after the error line
CASE 53
PRINT "File not found"
RESUME Next ' Skip error line, continue with next
CASE ELSE
PRINT "Unhandled error"
RESUME Label ' Jump to a specific label
' Or: RESUME 0 ' Retry the line that caused the error
' Or: ON ERROR GOTO 0 ' Disable error handler
END SELECT
Label:
PRINT "Continuing from label"
Graphics and Sound (QBasic/QuickBASIC)
Screen Modes
' Set screen mode
SCREEN 12 ' 640x480, 16 colors
' Set colors
COLOR 15, 1 ' White text on blue background
Basic Graphics
' Draw a point
PSET (100, 100), 14 ' Yellow point at (100,100)
' Draw a line
LINE (0, 0)-(200, 200), 12 ' Red line
' Draw a rectangle
LINE (50, 50)-(150, 150), 10, B ' Green rectangle
' Draw a filled rectangle
LINE (200, 50)-(300, 150), 9, BF ' Filled blue rectangle
' Draw a circle
CIRCLE (400, 100), 50, 13 ' Magenta circle, radius 50
Sound
' Basic sound (frequency, duration)
SOUND 440, 18.2 ' A4 note for 1 second
' Play notes
PLAY "C D E F G A B C"
Miscellaneous
Comments
' Single line comment (modern BASIC)
REM This is a traditional BASIC comment
Delay Execution
' Pause for 2 seconds
SLEEP 2
' Shorter pause (microseconds in some dialects)
SLEEP 0.5
System Commands
' Access operating system
SHELL "dir" ' Run DOS/Windows dir command
' Clear the screen
CLS
' Set cursor position
LOCATE 10, 20 ' Row 10, Column 20
' End program
END
DATA Statements
' Define data
DATA "John", 25, "Engineer"
DATA "Mary", 30, "Doctor"
' Read data
READ name$, age, job$
PRINT name$, age, job$
READ name$, age, job$
PRINT name$, age, job$
' Reset data pointer
RESTORE
Common Dialects and Their Special Features
QBasic/QuickBASIC
- Integrated development environment
- No line numbers required
- Libraries support via
.BI files - Graphics and sound support
Visual Basic
- Event-driven programming
- Forms and controls
- Object-oriented features
- Advanced APIs and COM integration
FreeBASIC
- Open source BASIC compiler
- High compatibility with QuickBASIC
- C libraries integration
- Extended functionality
Liberty BASIC
- Windows-focused BASIC variant
- Built-in GUI elements
- Less syntax than Visual Basic
- Ideal for small to medium applications
This cheat sheet covers the core syntax of BASIC programming languages. Keep in mind that specific implementations might have additional features or slight variations in syntax. Always refer to the documentation of your particular BASIC dialect for definitive information.