'=========================================================================== ' Subject: QBASIC LANGUAGE QUICK SUMMARY Date: 11-27-97 (09:24) ' Author: John P. Brown Code: Text ' Origin: J.P.Brown@bradford.ac.uk Packet: FAQS.ABC '=========================================================================== QBasic Language Quick Summary JPB 16/11/97 ----------------------------- Commas are used to separate variables and parameters, Colons are used to separate statements that appear on the same line. Don't use the underscore symbol < _ > in your variable names. DATA Types/Examples =================== Number of bytes Range % integer 2 bytes -32768 to 32767 & long integer 4 bytes -2147483648 to 2147483647 ! single precision 4 bytes 7 digits of sig. (default type) # double precision 8 bytes 15 digits of significance $ string up to 32767 up to 32767 characters examples: num% count& wage! wage balance# names$ integer long single single double string Note DEFtype statements give an alternative to using the symbols above but DATA-type suf. (%, &, !, #, or $) always takes precedence over a DEFtype. DEFINT letterrange [,letterrange]... variables that start with a DEFLNG letterrange [,letterrange]... letter from letterrange will all DEFSNG letterrange [,letterrange]... be of the specified type. DEFDBL letterrange [,letterrange]... example: DEFINT A-B,zz DEFSTR letterrange [,letterrange]... Anum Bnum Cnum zzNum (all integers) You can also use the DIM statement to specify a type, examples: DIM number AS DOUBLE double precision type. DIM address AS STRING variable length string. DIM code AS STRING * 10 fixed length string (10 characters in this case). DIM apples AS INTEGER integer type Mathematical operators Relational Operators ====================== ==================== + Addition = Equal to - Subtraction <> Not equal to * Multiplication > Greater than / Division < Less than ^ Exponention (raising to a power) >= Greater than or equal to \ Integer division <= Less than or equal to MOD Remainder division Constants, variables and arrays =============================== CONST define a symbolic constant/s ex. CONST daysperweek = 7 DIM declares an array DIM var(1 to 5) DIM element(9) (element 0 to 9) TYPE create user defined types. ex. TYPE typename ... END TYPE ERASE reinitialize elements of a static array (deallocates dynamic arrays) DATA stores numeric or string data to be used with READ (DATA 1, 2, 3, 4) READ used to read values from a DATA statement and assign them to variables. RESTORE used to change the READ order back to the start (or some other point) OPTION BASE declare the min. value for array sub. (don't use, use DIM) REDIM changes the space allocated to dynamically defined array. SWAP exchanges the contents of two variables. ex. SWAP num(1),num(2) UBOUND(array[,dimension]) returns highest subscript value. LBOUND(array[,dimension]) returns lowest subscript value. Control program flow (expr means numeric expression) ==================== (... means one or more statement lines) (see also "Set traps for events and errors") DO ... LOOP UNTIL expr Note: if the test is at the end of the DO UNTIL expr ... LOOP statements then statements will be done DO ... LOOP WHILE expr at least once. example DO ... LOOP WHILE DO WHILE expr ... LOOP DO ... LOOP REM always loop FOR i = 1 TO 100 STEP v ... NEXT i (v is step value, if omitted is 1) IF expr THEN ... ELSE ... if expr true do 1st ... if false do 2nd ... IF exp1 THEN ... ELSEIF exp2 THEN ... ELSEIF exp3 THEN ... ELSE ... END IF ON expr GOSUB sub1, sub2, sub3 In this example expr should = 1 - 3 GOTO Go to line number or label (use sparingly, if at all) SELECT CASE test_exp each case line looks for a match with test_exp. CASE expr1 ... there is one of these to match each valid case. CASE ELSE ... this is used for 'no match found' (ie. default). END SELECT terminates case statements block. END (prog, close files) also used with DEF, FUNCTION, IF, SELECT, SUB, TYPE SYSTEM closes all files and returns to operating system (or qbasic). STOP stops the program at any point (does not close files). EXIT DO, EXIT FOR, EXIT SUB, EXIT FUNCTION (gives a break out point). Define and call Basic procedures ================================ CALL subname[(parameters)] used to call a QBasic procedure. SUB subname ... END SUB (use EDIT -> New SUB to create your subroutine). DECLARE SUB subname(parameters) the editor puts this in your main program. FUNCTION fname ... END FUNCTION define a function type procedure (use EDIT). DECLARE fname(arguments) (this line added to main prog by editor after save). GOSUB this is the older way to call a subroutine (CALL is the modern way). RETURN returns from subroutine, this must be used to return from a GOSUB. DEF FName[(arguments)]expression (older way to define functions). DEF FName[(arguments)] ... END DEF (used with more than one statment line). RUN run a program (the one in memory or a specified alternative). CHAIN "aprogram.bas" transfers to another program, best avoid, poor struct. COMMON variables used to transfer variables to a chained program. SHELL run a DOS program or go to DOS shell (if no prog name). SHARED gives access to a variable without passing it to a procedure. STATIC preserves a variable value between procedure calls. Device input/output =================== INKEY$ gets code of key pressed (returns null string if no key pressed). INPUT Statement inputs values from keyboard, ex. INPUT "enter name",name$ LINE INPUT read entire line (including commas etc.) into a string. LPOS returns the current printer head position (in line buffer). PRINT writes to the screen display or a file. PRINT USING writes formatted output to screen or file. LPRINT similar to PRINT but output goes to line printer. LPRINT USING similar to PRINT USING but output goes to printer. SPC(num TAB(column) moves the cur. on to the spec. col.(PRINT and LPRINT) OPEN COM opens a communications port for input/output (baud rate etc.) STICK Function returns position of joystick A(x or y) or B(x or y). STRIG Function returns joystick trigger status (joystick buttons). INP returns a byte read from I/O port. OUT sends a byte to the specified port. WAIT pauses a program until a specified bit pattern received from a port. BEEP play a short tone via PC speaker to draw users attention. PLAY Statement play a tune specified by the command string. PLAY(dummy_numeric_argument) returns number of notes in background queue. SOUND freq,duration makes a sound using specified parameters. SCREEN control ============== CLS clears text or graphics viewport ie. current screen (3 other options) SCREEN Statement defines the screen characteristics, color mode etc.. SCREEN Function returns ascii code (or color in graphics mode of location) COLOR used to set the color for text or graphics (ex. COLOR foreg,backg). PALETTE and PALETTE USING used to set the graphics colors (EGA VGA). WIDTH sets the number of columns on the screen (or other device, or file). VIEW PRINT defines the text mode scrolling region (topline to bottom line) CSRLIN returns the current line (row) position of the cursor. POS(dummy_argument) gets the current cursor column position. LOCATE row,column reposition the cursor. VIEW define a restricted area for displaying graphics (viewport). WINDOW used to adjust the logical dimensions of the current viewport. SCREEN 0 Background and Foreground Colors (background colors go up to 7). ========================================== Color number Background Foreground Color number Foreground 0 Black Black 8 Gray 1 Blue Blue 9 Light Blue 2 Green Green 10 Light Green 3 Cyan Cyan 11 Light Cyan 4 Red Red 12 Light Red 5 Magenta Magenta 13 Light Magenta 6 Brown Brown 14 Yellow 7 White White 15 Bright White (add 16 to color number to get flashing color. ex. 31=flashing white text) Display graphic images ======================= CIRCLE used to draw a circle or ellipse. LINE used to draw a line or rectangle on the screen. PRESET set a pixel to the background color. PSET set a pixel to the foreground color. PAINT fill a graphic object on the screen with a color or a pattern. GET (Graphics) get the specified graphic rectangle and store in a file. PUT (Graphics) restore a graphic image (that was saved using GET). PCOPY used to copy contents of one screen page to another. PMAP used to map coordinates to logical or physical coordinates. POINT used to get the color of a pixel (or to get the pixel coordinates). DOS file system commands ========================= MKDIR directory$ makes a directory. CHDIR pathname$ changes directory. RMDIR directory$ deletes a directory. KILL file$ deletes a file (file$ can be "drive:\path\filename"). NAME oldfilename$ AS newfilename$ renames a file. File input/output ================= OPEN opens a file for input or output. CLOSE closes one or more files (opened by OPEN). GET (File I/O) reads a record from a random access file. PUT (File I/O) writes to a random access file (a record variable or buffer) WRITE writes data to sequential file. INPUT reads data from a sequential (or random) file. INPUT$ read (to a string) a sequence of characters from a file. LINE INPUT read all characters up to a from a sequential file. EOF(file LOC returns the current position in a file (binary, random, or seq) LOF(file SEEK Function returns the current file pointer position. SEEK Statement sets the file pointer position for the next read or write. FILEATTR returns either the file mode (append etc.) or the DOS file handle. FREEFILE returns the next valid and unused file number. LOCK prevents access to all or specific portions of file by network process UNLOCK unlocks portions of a shared file for use by other network programs. Conversion functions for use with random access files ===================================================== MKI$(integer-expression%) MKI$, MKL$, MKS$, and MKD$ convert MKL$(long-integer-expression&) numbers to numeric strings that can be MKS$(single-precision-expression!) stored in FIELD statement string MKD$(double-precision-expression#) variables. CVI(2-byte-numeric-string) CVL(4-byte-numeric-string) CVI, CVL, CVS, and CVD CVS(4-byte-numeric-string) convert 'strings' back to numbers. CVD(8-byte-numeric-string) CVSMBF(4-byte-numeric-string) converts to IEEE format float (single). CVDMBF(8-byte-numeric-string) " " " " double(double). MKSMBF$(single) converts from IEEE format to string. MKDMBF$(double) " " " " " " Memory Functions ================ CLEAR closes all files, inits. all variables and optionally sets stack size FRE returns the space available for strings, arrays or stack (""|-1|-2). PEEK(offset) returns the byte at the offset (in the current segment). POKE(offset,byte) place a byte in memory (within the current segment). BSAVE store a memory image of data or a program to a file (from current seg) BLOAD reload to memory data saved with BSAVE (to current segment). DEF SEG sets the segment value for subsequent PEEK, POKE, BLOAD, BSAVE VARSEG(variable) returns segment address of variable. VARPTR(variable) returns offset address of variable. Manipulate strings ================== ASC(s$) returns the numeric ascii code for first char. in string argument. CHR$(ascii_code) returns a one character string for the numeric argument. VAL(s$) returns the number value of a "string num representation". STR$(numeric_exp) returns a string representation (decimal) of the arg. HEX$(numeric_exp) " " " " (hexadecimal) " " . OCT$(numeric_exp) " " " " (octal) " " . LEN returns the number of char. in a string or bytes used by a variable. INSTR returns the position of the start of a string within a string. LEFT$(s$,n) returns n number of characters from the left of a string. RIGHT$(s$,n) returns n number of characters from the right of a string. MID$ Function returns a mid portion of a string at specified offset. MID$ Statement replaces a portion of a string with another string at offset. LSET left justifies a string. / also used with random access file buffers. RSET right justifies a string. \ and for converting variable record types. LTRIM$ removes the leading blank from a string(" hello" becomes "hello"). RTRIM$ removes the trailing blank from a string("hello " becomes "hello"). SPACE$(n) returns a string containing n space characters (an empty string). STRING$(n,ascii_value) similar to above but you can specify the fill char. UCASE$(s$) returns the string arg with all upper case lett.. LCASE$(s$) returns the string argument with all lower case letters. UCASE$(s$) returns the string argument with all upper case letters. Perform mathematical calculations (n can be a numeric expression) ================================= ABS(n) returns absolute value of n (ex. returns 5 for n = 5 or n = -5). SGN(n) returns the sign of n (+1 if n is +ve, -1 if n is -ve, 0 if n is = 0) INT(n) returns the integer part of n (n=9.9 returns 9 n= -9.9 returns -10). FIX(n) returns the integer part of n (n=9.9 returns 9 n= -9.9 returns -9). SQR(n) returns the square root of n. LOG(n) returns x where e^x=n ie. the natural log of n. EXP(n) returns e to the power of n, exponential of n (the natural anti log). ATN(n) returns the angle (in radians) where n is the tangent of the angle. COS(angle) returns the cosine of angle (angle in radians). SIN(angle) returns the sine of the angle (angle in radians). TAN(angle) returns the tangent of the angle (angle in radians). CSNG(n) returns n as a single precision value (number type conversion). CDBL(n) returns n as a double precision value. CINT(n) returns n as an integer (uses rounding not truncating). CLNG(n) returns n as an long integer (uses rounding not truncating). RANDOMIZE initialise the random number generator (ex. RANDOMIZE TIMER). RND returns a single precision with a value between 0 and 0.99... (0 - <1). Set traps for events and errors =============================== ERDEV returns int error code from the last device that declared an error. ERDEV$ returns the name of the device that generated a critical error. ERL returns the line number before the one that generated an error. ERR returns the error code for the last error that occurred. ERROR simulates an error of the type specified (ex. ERROR 222). RESUME continue program execution from an error trapping handler. KEY (Event Trapping) enable/disable key event trapping for specified key. COM enables/disables data communication event trapping on specified port. PEN Statement enable/disable light pen event trapping PLAY{ON|OFF|STOP} enable/disable/pause play event trapping. STRIG Statement enable/disable joystick button event trapping. TIMER Statement enable/disable timer event trapping. ON KEY Used to associate a subroutine with the specified ON COM event such as a key being pressed or when the specified ON PEN number of seconds have passed. ON PLAY Note: these do not enable event trapping, the ON STRIG statements above are used to enable/disable ON TIMER event trapping. ON TIMER ON ERROR GOTO Handler (go to 'error handler' on error condition) Misc ==== REM Precedes a comment (you can also use <'>) KEY Statement assign a string to a function key. KEY Function display function key assignment. TIME$ Function returns a string containing the system time (as "hh:mm:ss"). TIME$ Statement used to set the system time (as "hh:mm:ss"). DATE$ Function returns a string containing the system date (as "mm-dd-yyyy"). DATE$ Statement used to set the system date (as "mm-dd-yyyy") TIMER Function returns the number of seconds since midnight. SLEEP(n) waits for n seconds (waits till key pressed if n=0 or n not given) VARPTR$(commandstring$) returns a string for use with the DRAW or PLAY func.