BASIC Programming Syntax Cheat Sheet: Essential Commands and Structures

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

TypeDescriptionExample
INTEGERWhole numbersDIM age AS INTEGER
SINGLESingle-precision floatDIM price AS SINGLE
DOUBLEDouble-precision floatDIM pi AS DOUBLE
STRINGTextDIM name AS STRING
BOOLEANTrue/FalseDIM 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

OperatorDescriptionExample
+Additiona + b
Subtractiona – b
*Multiplicationa * b
/Divisiona / b
\Integer Divisiona \ b
MODModulusa MOD b
^Exponentiationa ^ b

Comparison Operators

OperatorDescriptionExample
=Equal toa = b
<>Not equal toa <> b
<Less thana < b
>Greater thana > b
<=Less than or equala <= b
>=Greater than or equala >= b

Logical Operators

OperatorDescriptionExample
ANDLogical ANDa AND b
ORLogical ORa OR b
NOTLogical NOTNOT a
XORExclusive ORa XOR b
EQVEquivalencea EQV b
IMPImplicationa IMP b

String Operators

OperatorDescriptionExample
+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

FunctionDescriptionExample
LEN(s$)String lengthLEN(“Hello”) ‘ Returns 5
LEFT$(s$, n)Leftmost n charactersLEFT$(“Hello”, 2) ‘ “He”
RIGHT$(s$, n)Rightmost n charactersRIGHT$(“Hello”, 2) ‘ “lo”
MID$(s$, p, n)n chars from position pMID$(“Hello”, 2, 3) ‘ “ell”
INSTR(s1$, s2$)Position of s2$ in s1$INSTR(“Hello”, “l”) ‘ 3
UCASE$(s$)Convert to uppercaseUCASE$(“Hello”) ‘ “HELLO”
LCASE$(s$)Convert to lowercaseLCASE$(“Hello”) ‘ “hello”
LTRIM$(s$)Remove leading spacesLTRIM$(” Hi”) ‘ “Hi”
RTRIM$(s$)Remove trailing spacesRTRIM$(“Hi “) ‘ “Hi”
TRIM$(s$)Remove leading and trailing spacesTRIM$(” Hi “) ‘ “Hi”
STR$(n)Convert number to stringSTR$(123) ‘ “123”
VAL(s$)Convert string to numberVAL(“123”) ‘ 123
CHR$(n)Character with ASCII code nCHR$(65) ‘ “A”
ASC(s$)ASCII code of first characterASC(“A”) ‘ 65
STRING$(n, c)String of n characters cSTRING$(5, “*”) ‘ “*****”

Math Functions

FunctionDescriptionExample
ABS(n)Absolute valueABS(-5) ‘ 5
INT(n)Integer part (truncate)INT(5.7) ‘ 5
FIX(n)Integer part (toward zero)FIX(-5.7) ‘ -5
SQR(n)Square rootSQR(16) ‘ 4
SIN(n)SineSIN(0) ‘ 0
COS(n)CosineCOS(0) ‘ 1
TAN(n)TangentTAN(0) ‘ 0
ATN(n)ArctangentATN(1) ‘ 0.7853981…
LOG(n)Natural logarithmLOG(2.718) ‘ 1
EXP(n)Exponential (e^n)EXP(1) ‘ 2.718…
RNDRandom number between 0 and 1RND ‘ 0.7533…(random)
SGN(n)Sign (-1, 0, or 1)SGN(-5) ‘ -1
CINT(n)Round to nearest integerCINT(5.5) ‘ 6
CSNG(n)Convert to single precisionCSNG(5) ‘ 5.0
CDBL(n)Convert to double precisionCDBL(5) ‘ 5.0

Date/Time Functions

FunctionDescriptionExample
DATE$Current system datePRINT DATE$ ‘ “01-01-2023”
TIME$Current system timePRINT TIME$ ‘ “13:45:30”
TIMERSeconds since midnightTIMER ‘ 49530.75
YEAR(d)Year from dateYEAR(“01/01/2023”) ‘ 2023
MONTH(d)Month from dateMONTH(“01/01/2023”) ‘ 1
DAY(d)Day from dateDAY(“01/01/2023”) ‘ 1
HOUR(t)Hour from timeHOUR(“13:45:30”) ‘ 13
MINUTE(t)Minute from timeMINUTE(“13:45:30”) ‘ 45
SECOND(t)Second from timeSECOND(“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.

Scroll to Top