QBasic/Appendix
Commands
ABS()
N = ABS(expression returning a numerical value)
Returns the 'absolute' value of the expression, turning a negative to a positive (e.g. -4 to 4)
PRINT ABS(54.345) 'This will print the value exactly as it is (54.345)
PRINT ABS(-43) 'This will print the value as (43)
ACCESS
OPEN "file.txt" FOR APPEND ACCESS WRITE
This sets the access of a file that has been declared into the program. There are three settings that the programmer can set. These are:
READ - Sets up the file to be read only, no writing. WRITE - Writes only to the file. Cannot be read. READ WRITE - Sets the file to both of the settings above.
APPEND means 'add' to the 'end of' the existing "file.txt". If omitted, any existing "file.txt" is over-written without warning
ASC()
PRINT ASC("t") 'Will print 116
Prints the ASCII code number of the character found within the brackets. If the programmer put in a string into brackets, only the first character of the string will be shown.
ATN()
ATN(expression)
Part of the inbuilt trigonometry functions. An expression that evaluates to a numeric vale is converted to it's Arc-Tangent.
angle = ATN( B ) angle2 = ATN( 23 / 34 )
BEEP
BEEP
The BIOS on the motherboard is instructed to emit a "Beep" sound from the PC 'speaker'. See also SOUND and PLAY.
CASE
SELECT CASE [variable] CASE [value]: [command] CASE ELSE: [command] END SELECT
Use this when using multiple values in your program and assigning them separate paths. This is an example of a program with no CASE commands that assigns different paths to values:
10 PRINT "1. Print 'path'" PRINT "2. Print 'hello" PRINT "3. Quit" INPUT "Enter a choice: "; a$ IF a$ = "1" THEN PRINT "path" GOTO 10 IF a$ = "2" THEN PRINT "hello" GOTO 10 IF a$ = "3" THEN END PRINT "That is not a valid choice" GOTO 10
This is what a program looks like with the CASE command:
PRINT "1. Print 'path'" PRINT "2. Print 'Hello'" PRINT "3. Quit" INPUT "Enter a choice: "; a$ SELECT CASE a$ CASE "1": PRINT "path" CASE "2": PRINT "Hello" CASE "3": END CASE ELSE: PRINT "That is not a valid choice" END SELECT
CHAIN
CHAIN {filename.format (parameters list)}
This 'calls' (transfers execution) to another program (typically another .bas file, a command (.bat or .cmd) script or an executable (.com, .exe) ).
Values may be passed directly in the invoking command (to files accepting command line parameters). Values may be passed to another basic script by using the 'COMMON' statement before the CHAIN command.
Control returns to the basic interpreter when the 'chained' program terminates.
CHDIR
CHDIR [directory name]
This is used for changing a directory. Used in conjunction with MKDIR and RMDIR. The directory name is declared exactly like in DOS PROMPT. For example:
CHDIR "c:/Program Files/QBasic_FIles/Testing_Files"
To use this command, the programmer will have to know how MS DOS and COMMAND PROMPT work.
CHR$()
This returns the string character symbol of an ASCII code value.
name$ = CHR$([acsii character code])
Often used to 'load' characters into string variables when that character cannot be typed (e.g. the Esc key or the F{n} (Function Keys) or characters that would be 'recognised' and acted upon by QBASIC interpreter (eg ", the double quote). Here is a list of some character codes :-
08 Backspace 09 Tab 27 Esc 34 Double quote 72 Up Arrow 75 Left Arrow 77 Right Arrow 80 Down Arrow
CINT()
This rounds the contents of the brackets to the nearest integer.
PRINT CINT(4573.73994596)
4574
CIRCLE
CIRCLE ([X Coordinate], [Y Coordinate]), [Radius], [Colour]
Lets the programmer display a circle. Like all graphics commands, it must be used with the SCREEN command.
CLEAR
CLEAR
Resets all variables, strings, arrays and closes all files. The reset command on QBasic.
CLOSE
CLOSE
Closes all open files
CLOSE #2
Closes only the file opened as data stream 2. Other files remain open
CLS
CLS
Clears the active screen. Erases all text, graphics, resets the cursor to the upper left (1,1), and also applies the current background color (this has to be set using the COLOR command) to the whole screen.
COLOR
COLOR [Text Colour], [Background Colour]
This lets you change the colour of the text and background used when next 'printing' to the current output window. It can be done like this:
COLOR 14, 01 PRINT "Yellow on Blue"
You have a choice of sixteen colours:
00: Black 08: Dark Grey 01: Dark Blue 09: Light Blue 02: Dark Green 10: Light Green 03: Dark Cyan 11: Light Cyan 04: Dark Red 12: Light Red 05: Dark Purple 13: Magenta 06: Orange Brown 14: Yellow 07: Grey 15: White
These values are the numbers that you put in the COLOR command.
Note Only screen modes 0, 7, 8, 9, 10 support a background color. To 're-paint' the whole screen in a background colour, use the CLS command.
COMMON
Declares a variable as 'global' which allows it's value to be accessed across multiple QBasic programs / scripts (see also the CHAIN command)
COMMON SHARED [variablename]
Each program that declares 'variablename' as COMMON will share the same value.
NOTE. All COMMON statements must appear at the start of the program (i.e. before any executable statements).
CONST
Fixes a variable so it can not be changed within the program.
CONST (name) {AS (type = INTEGER / STRING)} = (expression or value)
For example :-
CONST PI = 3.14159265
Assigns the value 3.14159265 to PI.
CONST PI2 = 2 * PI
PI must be assigned a value before it is used to calculate PI2. Typically all CONST are declared at the beginning of a program.
DATA
DATA [constant]
Use in conjunction with the READ and RESTORE command. Mostly used in programs dealing with graphics, this command lets QBasic read a large number of constants. The READ command accesses the data while the RESTORE command "refreshes" the data, allowing it to be used again.
DATE$
A system variable that always contains the current date as a string in mm-dd-yyyy format. Use it like this:
a$ = DATE$
DIM
This this is used to declare an array (early versions of Basic required all variables to be defined, not just arrays greater than 10)
DIM [Array Name] ([count],[count], ..)
The Array name can be of any type (Integer, Double, String etc). If not declared, single precision floating point is assumed. Strings can be 'declared' using $ sign (Integers with the '%' sign). The QBASIC interpreter tolerates numeric arrays of up to 10 count without these needing to be declared.
NOTE Early versions of QBasic did not explicitly set the contents of an array to zero (see CLEAR command)
DIM table%(100,2)
Create an integer array called table% containing 100x2 = 200 entries
DIM form$(5)
Create a string array called form$ containing 5 strings
DIM quotient(20) AS DOUBLE
Create an array called quotient that contains 20 double precision numbers
DO .. LOOP
DO [program] LOOP UNTIL [test condition becomes TRUE]
Used to create a loop in the program. The [condition] is tested only after the [program] code is executed for the first time (see also WHILE). For example:
num$ = 1 sum$ = 0 DO sum$ = 2 * num$ PRINT sum$ num$ = num$ + 1 LOOP UNTIL num$ = 13
This program outputs the Two Times Tables up to 12. The Reason why we put 13 is that the program stops at that point and does not continue the loop. If we put LOOP UNTIL num$ = 12 the last output on the screen would be "22".
See also EXIT DO
DRAW
DRAW "[string expression]"
Used to draw a straight line from the current 'cursor' position in the current colour. DRAW defines the direction (up, down etc.) and the length of the line (in pixels). For example:-
SCREEN 7 PSET (50, 50), 4 DRAW "u50 r50 d50 l50"
The letter in front of each number is the direction:
U = Up E = Upper-right D = Down F = Lower-right L = Left G = Lower-left R = Right H = Upper-left
The drawing 'cursor' is left at the position where the line ends. u50 draws from 50,50 upwards ending at 50,0 r50 draws from 50,0 to the right, ending at 100,0 d50 draws from 100,0 downwards, ending at 100,50 l50 draws from 100,50 to the left, ending at 50,50
The example shown will thus draw a red 'wire frame' square.
See also LINE and CIRCLE commands.
Note: Pixels are square. The diagonal from 0,0 to 100,100 will be 100 * root(2) pixels long (i.e. 141)
END
END
Signifies the end of the program. When QBasic sees this command it usually comes up with a statement saying: "Press Any Key to Continue".
END IF
END IF
Ends the program if a condition is reached.
ENVIRON
ENVIRON [string expression]
NOTE: If you are running QBasic on a Windows system, you wont be able to use this command.
This command lets you set an environment variable for the duration of the session. On exit from the QBasic.exe interpreter, the variables revert to their original values.
EOF()
This checks if there are still more data values to be read from the file specified in (). EOF() returns a boolean / binary value, a one or zero. 0 if the end of file has not been reached, 1 if the last value in the file has been read (see also LINE INPUT)
OPEN File.txt FOR INPUT AS #1 DO INPUT #1, text$ PRINT text$ LOOP UNTIL EOF(1) END
Note that, since the INPUT is executed before UNITIL is reached, File.txt must contain at least one line of text - if the file is empty, you will receive an 'ERROR (62) Input past end of file'.
ERASE
ERASE [arrayname] [,]
Used to erase all dimensioned arrays.
ERROR
System variable holding a numeric value relating to the processing of the previous line of code. If the line completed without error, ERROR is set to 0. If the line failed, ERROR is set to one of the values shown below. Most commonly used to redirect program flow to error handling code as in :-
ON ERROR GOTO [line number / label]
If ERROR is non=zero, program flow jumps to the line number or label specified. If ERROR is zero, program flow continues with the next line below.
To manually test your program and check to see if the error handling routine runs OK, ERROR can be set manually :-
ERROR [number]
Set ERROR = number
The error numbers are as follows:
1 NEXT without FOR 39 CASE ELSE expected 2 Syntax Error 40 Variable required 3 RETURN without GOSUB 50 FIELD overflow 4 Out of DATA 51 Internal error 5 Illegal function call 52 Bad file name or number 6 Overflow 53 File not found 7 Out of memory 54 Bad file mode 8 Label not defined 55 File already open 9 Subscript out of range 56 FIELD statement active 10 Duplicate definition 57 Device I/O error 11 Division by zero 58 File already exists 12 Illegal in direct mode 59 Bad record length 13 Type mismatch 61 Disk full 14 Out of string space 62 Input past end of file 16 String formula too complex 63 Bad record number 17 Cannot continue 64 Bad file name 18 Function not defined 67 Too many files 19 No RESUME 68 Device unavailable 20 RESUME without error 69 Communication-buffer overflow 24 Device timeout 70 Permission denied 25 Device Fault 71 Disk not ready 26 FOR without NEXT 72 Disk-media error 27 Out of paper 73 Advanced feature unavailable 29 WHILE without WEND 74 Rename across disks 30 WEND without WHILE 75 Path/File access error 33 Duplicate label 76 Path not found 35 Subprogram not defined 37 Argument-count mismatch 38 Array not defined
Note that ERROR is set when execution fails, not when the code is 'read' - so, for example, a 'divide by 0' will be found before the result is assigned to a non-existent array variable or written to a non-existent file.
EXIT
Allows the immediate exit from a subroutine or a loop, without processing the rest of that subroutine or loop code
EXIT DEF
Exits from a DEF FN function.
EXIT DO
Exits from a DO loop, execution continues with the command directly after the LOOP command
EXIT FOR
Exits from a FOR loop, execution continues with the command directly after the NEXT command
EXIT FUNCTION
Exits a FUNCTION procedure, execution continues with the command directly after the function call
EXIT SUB
Exits a SUB procedure.
FOR .. NEXT
FOR [variable name] = [start value] TO [end value] {STEP n}
[program code]
NEXT [variable name]
The variable is set to the [start value], then program code is executed and at the Next statement the variable is incremented by 1 (or by the STEP value, if any is specified). The resulting value is compared to the [end value] and if not equal program flow returns to the line following the FOR statement.
For example:
FOR a = 200 TO 197 STEP-1 PRINT a NEXT a
200 199 198
Care must be taken when using STEP, since it is quite possible to step past the (end value) with the result that the FOR loop will run 'for ever' (i.e. until the user aborts the interpreter or an error occurs), for example :-
FOR a = 200 TO 197 STEP-2 PRINT a NEXT a
200 198 196 194 192 ... 0 -2 -4 ... -32768 ERROR overflow
GOSUB
GOSUB [subroutine line number / label]
Command processing jumps to the subroutine specified. When the RETURN command is encountered, processing returns to this point and continues with the line below the GOSUB.
IF
IF [variable or string] [operator] [variable or string] THEN [command] {ELSE [command]}
Compares variables or strings. For example, if you wanted to examine whether or not a user-entered password was the correct password, you might enter:
IF a$ = "password" THEN PRINT "Password Correct"
Where a$ is the user entered password. Some operators include:
"="- equal to
"<"- less than (only used when variable or string is a number value)
">"- greater than (only used when variable or string is a number value)
"<>"- does not equal
"<="- less than or equal to (only used when variable or string is a number value)
">="- greater than or equal to (only used when variable or string is a number value)
One can also preform actions to number values then compare them to other strings or variables using the if command, such as in the below examples:
IF a+5 = 15 THEN PRINT "Correct"
IF a*6 = b*8 THEN PRINT "Correct"
INCLUDE
QBasic supports the use of include files via the $INCLUDE directive:
'$INCLUDE: 'foobar.bi'
Note that the include directive is prefixed with an apostrophe, dollar, and that the name of the file for inclusion is enclosed in single quotation mark symbols.
INKEY$
[variable] = INKEY$
This is used when you want a program to function with key input from the keyboard. Look at this example on how this works:
a$ = INKEY$ PRINT "Press Esc to Exit" END IF a$ = CHR$(27)
You can use this in conjunction with the CHR$ command or type the letter (e.g. A).
INPUT
INPUT [String Literal] [,or;] [Variable]
Displays the String Literal, if a semi colon follows the string literal, a question mark is displayed, and the users input until they hit return is entered into the variable. The variable can be a string or numeric. If a user attempts to enter a string for a numeric variable, the program will ask for the input again. The String Literal is option. If the string literal is used, a comma (,) or semicolon (;) is necessary.
INPUT #
INPUT #n [String Literal] [,or;] [Variable]
Reads a string / value from the specified file stream (see also LINE INPUT #)
INPUT #1, a$, b$, n, m
Reads 4 values from the file that is OPEN as #1. a$ is assigned all text until a ',' (comma) or end of line is reached, b$ the next segment of text, then two numeric values are interpreted and assigned to n and m.
Note that, within the file, numbers can be separated by 'anything' - so, if a number is not found (for 'n' or 'm') on the current 'line' of the file, the rest of the file will be searched until a number is found. Input is then left 'pointing' at the position in the file after the last number required to satisfy the input statement (see also 'seek #' command)
LEFT$()
A$ = LEFT$(B$,N)
A$ is set to the left most characters of B$ ending at the Nth character.
A$ = LEFT$("Get the start only",4)
returns "Get "
See also RIGHT$(), MID$().
LET
LET [variable] = [value]
Early versions of the QBasic.exe command interpreter required use of the 'LET' command to assign values to variables. Later versions did not.
LET N = 227 / 99 LET A$="a line of simple text"
is equliavent to :-
N = 227 / 99 A$="a line of simple text"
LINE
LINE ([X], [Y]) - ([X], [Y]), [Colour Number]
Used for drawing lines in QBasic. The first X and Y are used as coordinates for the beginning of the line and the second set are used for coordinating were the end of the line is. You must put a SCREEN command at the beginning of the program to make it work.
Note. When in SCREEN 13, the Colour Number == the Palette number
LINE INPUT #
LINE INPUT #1, a$
Reads a complete line as text characters from the file OPEN as stream #1 and places it in a$.
To find the 'end of line', the QBasic interpreter seaches for the 'Carriage Return' + 'Line Feed' (0x0D, 0x0A) characters. When reading text files created on UNIX/LINUX systems (where the 'Line feed' 0x0A is used on it's own to signify 'end of line'), LINE INPUT will not recognise the 'end of line' and will continue to input until the end of file is reached. For files exceeding 2k characters, the result is an "Out of String Space" Error as a$ 'overflows'. One solution is to use a text editor able to handle UNIX files to open and 'save as' before atempting to process the file using QBasic.
LOOP
DO [Program] LOOP UNTIL [condition]
Used to create a loop in the program. This command checks the condition after the loop has started. This is used in conjunction with the DO command.
LPRINT
LPRINT [statement or variable]
Prints out text to a printer.
OPEN
OPEN "[(path)\8.3 file name.ext]" (FOR {INPUT/OUTPUT} AS #{n})
This opens a file. You have to give the DOS file name, for example:
OPEN "data.txt" FOR INPUT AS #1
Opens the existing file data.txt for reading as data stream #1. Since no path is specified, the file must be in the same folder as the QBasic.exe - if not, processing halts with a 'file not found' error
OPEN "C:\TEMP\RUN.LOG" FOR OUTPUT AS #2
Opens an empty file named RUN.LOG in the C:\TEMP folder for writing data stream #2. Any existing file of the same name is replaced.
PALETTE
PALETTE[palette number, required colour]
For VGA (SCREEN mode 13) only, sets the Palette entry to a new RGB color. The palette number must be in the range 1-256. The required colour is a LONG integer created from the sum of (required Blue * 65536) + (required Green * 256) + required Red.
READ
READ [Variable]
Used in conjunction with the DATA command, this command lets QBasic read data. This is mostly used when dealing with large quantities of data like bitmaps.
REM or '
REM {comments}
' {comments}
When the interpreter encounters REM or " ' " (a single quote) at the start of a line, the rest of the line is ignored
RETURN
RETURN
Signifies that it is the end of a subroutines
PLAY
PLAY "[string expression]"
Used to play notes and a score in QBasic on a computer equipped with a MIDI sound-card (all modern computer motherboards with built-in sound support MIDI). The tones are indicated by letters A through G. Accidentals are indicated with a "+" or "#" (for sharp) or "-" (for flat) immediately after the note letter. See this example:
PLAY "C C# C C#"
Whitespaces are ignored inside the string expression. There are also codes that sert the duration, octave and tempo. They are all case-insensitive. PLAY executes the commands or notes the order in which they appear in the string. Any indicators that change the properties are effective for the notes following that indicator.
Ln Sets the duration (length) of the notes. The variable n does not indicate an actual duration
amount but rather a note type; L1 - whole note, L2 - half note, L4 - quarter note, etc.
(L8, L16, L32, L64, ...). By default, n = 4.
For triplets and quintets, use L3, L6, L12, ... and L5, L10, L20, ... series respectively.
The shorthand notation of length is also provided for a note. For example, "L4 CDE L8 FG L4 AB"
can be shortened to "L4 CDE F8G8 AB". F and G play as eighth notes while others play as quarter notes.
On Sets the current octave. Valid values for n are 0 through 6. An octave begins with C and ends with B.
Remember that C- is equivalent to B.
< > Changes the current octave respectively down or up one level.
Nn Plays a specified note in the seven-octave range. Valid values are from 0 to 84. (0 is a pause.)
Cannot use with sharp and flat. Cannot use with the shorthand notation neither.
MN Stand for Music Normal. Note duration is 7/8ths of the length indicated by Ln. It is the default mode.
ML Stand for Music Legato. Note duration is full length of that indicated by Ln.
MS Stand for Music Staccato. Note duration is 3/4ths of the length indicated by Ln.
Pn Causes a silence (pause) for the length of note indicated (same as Ln).
Tn Sets the number of "L4"s per minute (tempo). Valid values are from 32 to 255. The default value is T120.
. When placed after a note, it causes the duration of the note to be 3/2 of the set duration.
This is how to get "dotted" notes. "L4 C#." would play C sharp as a dotted quarter note.
It can be used for a pause as well.
MB MF Stand for Music Background and Music Foreground. MB places a maximum of 32 notes in the music buffer
and plays them while executing other statements. Works very well for games.
MF switches the PLAY mode back to normal. Default is MF.
PRINT [Argument] [,or;] [Argument]...
Displays text to the screen. The Argument can be a string literal, a string variable, a numeric literal or a numeric variable. All arguments are optional.
PRINT #[n] [,or;] [Argument]...
Saves data to the file that is 'OPEN FOR OUTPUT AS #[n]'
PSET
PSET ([X coordinate],[Y coordinate]), [Pixel Colour]
This command displays pixels, either one at a time or a group of them at once. For the command to work, the program must have a SCREEN command in it.
SCREEN
SCREEN [Screen Mode Number]
This command is used for displaying graphics on the screen. There are ten main types of screen modes that can be used in QBasic depending on the resolution that you want. Here is a list of what screen modes you can choose from:
SCREEN 0: Textmode, cannot be used for graphics. This the screen mode that text based programs run on.
SCREEN 1: 320 x 200 Resolution. Four Colours
SCREEN 2: 640 x 200 Resolution. Two Colours (Black and White)
SCREEN 7: 320 x 200 Resolution. Sixteen Colours
SCREEN 8: 640 x 200 Resolution. Sixteen Colours
SCREEN 9: 640 x 350 Resolution. Sixteen Colours
SCREEN 10: 640 x 350 Resolution. Two Colours (Black and White)
SCREEN 11: 640 x 480 Resolution. Two Colours
SCREEN 12: 640 x 480 Resolution. Sixteen Colours
SCREEN 13: 320 x 200 Resolution. 256 Colours. (Recommended)
Note. In SCREEN 13 you have a colour Palette of 256 colours. The PALETTE is pre-set by Windows however you can change the RGB values using the PALETTE command.
SEEK
SEEK #[file number], 1
Repositions the 'input #' pointer to the beginning of the file.
SLEEP
SLEEP [n]
Execution is suspended for n seconds
SOUND
SOUND [frequency], [duration]
Unlike the BEEP command, this produces a sound from the PC speakers that is of a variable frequency and duration. The frequency is measured in Hertz and has a range from 37 to 32767. Put in one of these numbers in the frequency section. The duration is clock ticks that is defaulted at 18.2 ticks per second.
STR$
Converts a numeric value into a text (string) character
A$ = STR$(expression yielding a numeric value)
The numeric value is converted into text characters and placed into A$. Used to convert numbers into text (where they can be formatted, for example, by adding leading zeros or '+', '-' characters)
WARNING - a leading 'space' is added. STR$(123) = " 123" and not "123" as might be expected
See also CHR$ for converting an ascii value into a string character.
See also LEFT$, MID$, RIGHT$ for extracting sub-strings from a line of text.
SYSTEM
SYSTEM
The .bas exits, the QBasic.exe interpreter is closed and 'control' passes to the Command Window c:\ prompt (or next line of a calling .cmd script etc.).
THEN
[Command] [variable] = [value] THEN GOTO [line command value]
Used in conjunction with the GOTO or IF condition commands. It tells the computer what to do if a certain condition has been met.
TO
[Command] [Variable] = [Value] TO [Value]
Usually used to input a number of variables.
FOR a = 400 TO 500 PRINT a NEXT a
This example will print all numbers from 400 to 500. Instead of declaring all values separately, we can get them all declared in one go.
USING
USING "format";
Used to format the output of data from PRINT commands. Normally, the QBasic interpreter will print a number as 8 characters with as many leading spaces as necessary. To change this behavour, the USING command can be used to format the output. For example ..
IF n > 99 THEN PRINT #1, USING "###"; n; ELSE IF n > 9 THEN PRINT #1, USING "0##"; n; ELSE PRINT #1, USING "00#"; n;
.. will output n from 0 to 999 with leading zeros. Note the ';' after the n. This means 'don't start a new line' and results in the next PRINT #1 adding data directly after the comma (',') Qbasic automatically inserts instead of a line line.
VAL()
name=VAL([variable$])
Converts the [variable string] contents into a numeric value so it can be used in calculations. If (name) is an INTEGER type, the VAL is rounded down. See also STR$.
A$ = "2 + 3" B = VAL(A$) PRINT A$ is B
2 + 3 is 5
WHILE ... WEND
WHILE {NOT} [test condition is true]
[program code to execute]
WEND
The condition is tested and if true (or NOT true) the [program] code is executed until WEND is reached, at which point control passes back to the WHILE line.
WHILE NOT (EOF(1)) LINE INPUT #1, A$ PRINT #2, A$ WEND
While the end of file #1 has not been reached, read each complete line and write it to file #2.
Unlike FOR and DO, it is not possible to EXIT from a WHILE loop
Source Code
WAP TO PRINT ODD NUMBERS AUTOMATICALLY FROM 1 WITHIN AN ARRAY OF SIZE 10