Tech

C64 Basic V2 cheat sheet

C64 Basic V2 cheat sheet. Explore our ultimate quick reference for C64 Basic V2.

This C64 Basic V2 cheat sheet is a comprehensive guide designed to help both beginners and seasoned programmers navigate the intricacies of programming on the Commodore 64. It offers a wide range of information, from coding tips and command overviews to practical code snippets for immediate application. Whether you're looking to understand program flow, manage data, or simply start coding on this classic platform, this cheat sheet is an invaluable resource for quick reference and learning.

Basics of Basic V2

Coding Tips

  • Program Editing: Add, overwrite, or delete BASIC lines using line numbers.
  • Viewing Code: Use LIST to display the entire BASIC program.
  • Navigation: Employ line numbers as labels for GOTO jump commands.
  • Execution: Start your program with RUN; halt it with RUN/STOP key.
  • Memory Management: BASIC programs reside temporarily in memory. Save your work with SAVE and load with LOAD to prevent loss.

Hints: Effective BASIC Programming on C64

  • Command Completion: Press RETURN to execute a BASIC command.
  • Command Separation: Use a colon : to divide multiple commands in a single line.
  • Line Length: Max of 80 characters (or 40 over 2 lines); use abbreviations or compilers for longer lines. Editing long lines can be tricky.
  • Variables: Usable in direct mode but with limitations. Variables reset when editing in direct mode.
  • Line Numbering: Opt for large steps (e.g., 10, 20, 30) to simplify insertion and reordering. Renumbering tools are external.
  • Variable Naming: Avoid BASIC keywords and reserved names like ST for variables.
  • Line Number Range: Program line numbers range from 0 to 63999.

Basic V2 Commands

Mathematical Operations

  • ABS: Absolute value of a number.
  • AND: Logical AND.
  • ASC: ASCII value of a character.
  • ATN: Arctangent of a number.
  • COS: Cosine of an angle.
  • EXP: Exponential function.
  • INT: Integer part of a number.
  • LOG: Natural logarithm.
  • NOT: Logical NOT.
  • OR: Logical OR.
  • RND: Random number generator.
  • SGN: Sign function.
  • SIN: Sine of an angle.
  • SQR: Square root.
  • TAN: Tangent of an angle.

File Management

  • CLOSE: Close a file.
  • LOAD: Load a program from tape or disk.
  • OPEN: Open a file.
  • SAVE: Save a program to tape or disk.
  • VERIFY: Verify tape or disk data.

Input and Output

  • CMD: Command device redirection.
  • GET: Get a character from the keyboard.
  • GET#: Get a character from a device.
  • INPUT: Input data from the keyboard.
  • INPUT#: Input data from a device.
  • LIST: List a BASIC program.
  • PRINT: Print data to the screen.
  • PRINT#: Print data to a device.

Program Flow Control

  • CONT: Continue execution after a STOP.
  • FOR: For loop start.
  • GOSUB: Go to subroutine.
  • GOTO: Go to line.
  • IF: Conditional execution.
  • NEXT: For loop end.
  • ON: Conditional on GOTO/GOSUB.
  • REM: Remark/comment.
  • RESTORE: Reset READ pointer.
  • RETURN: Return from subroutine.
  • RUN: Run a BASIC program.
  • STOP: Stop program execution.
  • THEN: Part of IF statement.
  • TO: Part of FOR loop.
  • WAIT: Wait for a memory location to change.

Data and Variable Management

  • DATA: Data storage for READ command.
  • DEF: Define a function.
  • DIM: Dimension an array.
  • END: End program execution.
  • READ: Read data from DATA statements.
  • LET: Assign a value to a variable (implicit in expressions).

String Manipulation

  • CHR$: Convert ASCII code to character.
  • LEFT$: Left substring.
  • LEN: Length of a string.
  • MID$: Middle substring.
  • RIGHT$: Right substring.
  • STR$: Convert number to string.
  • VAL: Convert string to number.

System Commands

  • CLR: Clear variables and reset system.
  • FRE: Free memory.
  • NEW: Clear current program.
  • PEEK: Read memory location.
  • POKE: Write to memory location.
  • POS: Cursor position.
  • SPC: Space in PRINT statements.
  • STATUS/ST: I/O operation status.
  • STEP: Increment step in FOR loops.
  • SYS: Execute machine language program.
  • TAB: Horizontal tab in PRINT statements.
  • TIME/TI: Current jiffy clock time.
  • TIME$/TI$: Current time in string format.
  • USR: Call machine language routine.
  • π (PI): Mathematical constant Pi.

A-Z of Basic Commands: In Detail

ABS

TYPE: Function-Numeric

FORMAT: ABS(<expression>)

Action: Returns the absolute value of the number, which is its value without any signs. The absolute value of a negative number is that number multiplied by -1.

EXAMPLES of ABS Function:

10 X = ABS(Y)
10 PRINT ABS(X*J)
10 IF X = ABS(X) THEN PRINT "POSITIVE"

AND

TYPE: Operator

FORMAT: <expression> AND <expression>

Action: AND is used in Boolean operations to test bits. It is also used in operations to check the truth of both operands. In Boolean algebra, the result of an AND operation is 1 only if both numbers being ANDed are 1. The result is 0 if either or both are 0 (false). The Commodore 64 performs the AND operation on numbers in the range from -32768 to +32767. Any fractional values are not used, and numbers beyond the range will cause an ?ILLEGAL QUANTITY error message. When converted to binary format, the range allowed yields 16 bits for each number. Corresponding bits are ANDed together, forming a 16-bit result in the same range.

EXAMPLES of 1-Bit AND operation:

  • 0 AND 0 => 0
  • 1 AND 0 => 0
  • 0 AND 1 => 0
  • 1 AND 1 => 1

ASC

TYPE: Function-Numeric

FORMAT: ASC(<string>)

Action: ASC returns a number from 0 to 255 corresponding to the Commodore ASCII value of the first character in the string. If the string is empty, an ?ILLEGAL QUANTITY error results. To avoid this error when a string might be empty, add CHR$(0) to the end of the string. This function is useful for converting characters to their ASCII numerical representations, as detailed in the Commodore ASCII value table.

EXAMPLES OF ASC Function:

10 PRINT ASC("Z")
20 X = ASC("ZEBRA")
30 J = ASC(J$)

EXAMPLE of ASC Function Avoiding ILLEGAL QUANTITY ERROR:

30 J = ASC(J$ + CHR$(0))

ATN

TYPE: Function-Numeric

FORMAT: ATN(<number>)

Action: ATN is a mathematical function that returns the arctangent of the number provided. The result is the angle, in radians, whose tangent is the number given. The resulting angle is always in the range of -pi/2 to +pi/2. This function is useful for trigonometric calculations where you need to convert a tangent value back into an angle.

EXAMPLES of ATN Function:

10 PRINT ATN(0)
20 X = ATN(J)*180/π : REM CONVERT TO DEGREES

CHR$

TYPE: Function-String

FORMAT: CHR$ (<number>)

Action: CHR$ converts a Commodore ASCII code into its corresponding character. The function takes a number from 0 to 255, representing the ASCII code, and returns the character equivalent. It's a useful tool for generating characters from their ASCII values, particularly in scenarios requiring control characters or graphical symbols not directly accessible from the keyboard. Refer to Appendix C for a comprehensive list of characters and their codes. An ?ILLEGAL QUANTITY error message will appear if the number is outside the 0 to 255 range.

EXAMPLES of CHR$ Function:

10 PRINT CHR$(65) : REM 65 = UPPER CASE A
20 A$=CHR$(13) : REM 13 = RETURN KEY
50 A=ASC(A$) : A$ = CHR$(A) : REM CONVERTS TO C64 ASCII CODE AND BACK

CLOSE

TYPE: I/O Statement

FORMAT: CLOSE <file number>

Action: CLOSE terminates the connection to a data file or device channel previously established with the OPEN statement. This operation is crucial for storage devices like cassette tapes and disks, as it ensures any data stored in buffers is properly written to the device, completing the file. Without closing, files may be left incomplete and therefore unreadable. While not always necessary for other types of devices, closing files helps to free up memory for additional file handling. Refer to the documentation for your external devices for device-specific implications of the CLOSE operation.

EXAMPLES of CLOSE Statement:

10 CLOSE 1
20 CLOSE X
30 CLOSE 9*(1+J)

CLR

TYPE: Statement

FORMAT: CLR

Action: CLR clears the RAM memory of variables, arrays, GOSUB return addresses, FOR...NEXT loop information, user-defined functions, and files, making space available for new data. While the existing BASIC program in memory remains intact, the aforementioned elements are erased, essentially resetting the program environment to a clean state without affecting the program code itself. It's important to note that files open to disk or cassette are not properly closed with CLR, potentially leaving the disk drive to consider the file still open. For proper file closure, see the CLOSE statement.

EXAMPLE of CLR Statement:

10 X=25
20 CLR
30 PRINT X

RUN

Output will be 0 since the CLR statement has reset all variables, making X undefined after CLR is executed, and attempting to print X results in an error or unexpected behavior, depending on the implementation of BASIC.

CMD

TYPE: I/O Statement

FORMAT: CMD <file number> [,string]

Action: CMD redirects the primary output from the TV screen to a specified file, which could be on disk, tape, a printer, or an I/O device like a modem. The file must be opened beforehand using an OPEN statement. Optionally, a string can be sent to the file as part of the CMD operation, useful for adding titles to printouts. While CMD is active, PRINT and LIST commands will output to the selected file instead of the screen. To redirect output back to the screen, ensure a blank line is sent to the CMD device before it is closed. Errors will automatically redirect output back to the screen, but the device will not stop expecting data until a blank line is sent.

EXAMPLES of CMD Statement:

OPEN 4,4: CMD 4,"TITLE" : LIST: REM LISTS PROGRAM ON PRINTER
PRINT#4: CLOSE 4: REM UN-LISTENS AND CLOSES PRINTER

10 OPEN 1,1,1,"TEST" : REM CREATE SEQ FILE
20 CMD 1 : REM OUTPUT TO TAPE FILE, NOT SCREEN
30 FOR L = 1 TO 100
40 PRINT L: REM PUTS NUMBER IN TAPE BUFFER
50 NEXT
60 PRINT#1 : REM UNLISTEN
70 CLOSE 1 : REM WRITE UNFINISHED BUFFER, PROPERLY FINISH

CONT

TYPE: Command

FORMAT: CONT

Action: CONT resumes the execution of a program that was previously halted by a STOP statement, an END statement, or the pressing of the <RUN/STOP> key. It allows the program to restart from the exact point it was interrupted, providing a seamless continuation. This feature is particularly useful for debugging or examining the program's behavior by inserting STOP statements at critical points to inspect variables or program flow. However, attempting to CONTINUE after modifying the program, encountering an error, or causing an error before issuing the CONT command will result in a "CAN'T CONTINUE" error message.

EXAMPLE of CONT Command:

10 PI=0:C=1
20 PI=PI+4/C-4/(C+2)
30 PRINT PI
40 C=C+4:GOTO 20

This program attempts to calculate the value of PI. To observe its progress, you can temporarily stop it using the <RUN/STOP> key, inspect variables like C with PRINT C, and then continue execution with CONT.

COS

TYPE: Function

FORMAT: COS (<number>)

Action: COS calculates the cosine of the specified angle, where the angle is given in radians. This function is essential in trigonometry for calculations involving angles and circles. It's commonly used in graphics programming, animations, and mathematical computations where trigonometric functions play a crucial role.

EXAMPLES of COS Function:

10 PRINT COS(0)
20 X = COS(Y*π/180) : REM CONVERT DEGREES TO RADIANS

DATA

TYPE: Statement

FORMAT: DATA <list of constants>

Action: DATA statements are used to store a list of constants within a BASIC program. These constants are accessed and used by the program through the READ statement, which sequentially retrieves the values stored in DATA statements. DATA statements do not need to be executed directly; their presence in the program is sufficient, making them commonly placed at the end of the program. DATA is read in the order it appears, from the lowest to the highest numbered line. Special attention is needed when DATA contains characters such as commas, colons, spaces, and other symbols, as these values must be enclosed in quotation marks to be interpreted correctly.

EXAMPLES of DATA Statement:

10 DATA 1,10,5,8
20 DATA JOHN,PAUL,GEORGE,RINGO
30 DATA "DEAR MARY, HOW ARE YOU, LOVE, BILL"
40 DATA -1.7E-9, 3.33

DEF FN

TYPE: Statement

FORMAT: DEF FN <name>(<variable>) = <expression>

Action: DEF FN creates a user-defined function, allowing the encapsulation of a mathematical formula for reuse throughout a BASIC program. This capability is particularly useful for condensing complex or lengthy formulas into a simple function call, enhancing readability and maintainability. The function name starts with FN followed by a valid variable name, which can be one or two characters long, with the first character being a letter and the second, if present, either a letter or a digit. A user-defined function needs to be executed once to be set; any attempts to redefine it within the same program execution are ignored.

EXAMPLES of DEF FN Statement:

10 DEF FN A(X)=X+7
20 DEF FN AA(X)=Y*Z
30 DEF FN A9(Q) = INT(RND(1)*Q+1)

EXAMPLES of FN Use:

40 PRINT FN A(9)
50 R=FN AA(9) ; REM In this case, the 9 is ignored in terms of the function's calculation.
60 G=G+FN A9(10)

In these examples, the user-defined functions are utilized within the program to perform calculations, demonstrating the versatility and efficiency of defining custom functions in BASIC programming.

DIM

TYPE: Statement

FORMAT: DIM <variable>(<subscripts>)[ <variable>(<subscripts>)...]

Action: DIM is used to define arrays or matrices of variables, enabling indexed variable access via subscripts. The subscript ranges from zero to the specified maximum in the DIM statement, with the upper limit set at 32767. Each array must be dimensioned exactly once to prevent a 'REDIM'D ARRAY' error. DIM statements are typically placed at the beginning of a program to outline all necessary arrays upfront. Arrays can be multidimensional, up to 255 dimensions, and their size is only limited by the available RAM. Arrays can hold standard numeric variables, strings (indicated by $ after the variable name), or integers (indicated by %).

EXAMPLES of DIM Statement:

10 DIM A(100)
20 DIM Z(5,7), Y(3,4,5)
30 DIM Y7%(Q)
40 DIM PH$(1000)
50 F(4)=9 ; REM AUTOMATICALLY PERFORMS DIM F(10)

EXAMPLE of FOOTBALL SCORE-KEEPING Using DIM:

10 DIM S(1,5), T$(1)
20 INPUT "TEAM NAMES"; T$(0), T$(1)
30 FOR Q = 1 TO 5: FOR T = 0 TO 1
40 PRINT T$(T), "SCORE IN QUARTER", Q
50 INPUT S(T,Q): S(T,0) = S(T,0) + S(T,Q)
60 NEXT T, Q
70 PRINT CHR$(147); "SCOREBOARD"
80 PRINT "QUARTER"
90 FOR Q = 1 TO 5
100 PRINT TAB(Q*2+9), Q;
110 NEXT: PRINT TAB(15), "TOTAL"
120 FOR T = 0 TO 1: PRINT T$(T);
130 FOR Q = 1 TO 5
140 PRINT TAB(Q*2+9), S(T,Q);
150 NEXT: PRINT TAB(15), S(T,0)
160 NEXT

In these examples, the DIM statement is used for declaring single and multidimensional arrays, illustrating how they can organize data efficiently in a BASIC program.

END

TYPE: Statement

FORMAT: END

Action: The END statement terminates the execution of a BASIC program and returns control to the user, displaying the READY message. It can be used multiple times within a program to define explicit exit points. Although not strictly required (a program can technically end by running out of lines to execute), it is good practice to include an END statement to clearly indicate the program's intended termination point. Unlike the STOP statement, which halts execution and displays "BREAK IN LINE XX," END simply concludes the program and shows "READY", but like STOP, execution can be resumed with the CONT command.

EXAMPLES of END Statement:

10 PRINT "DO YOU REALLY WANT TO RUN THIS PROGRAM"
20 INPUT A$
30 IF A$ = "NO" THEN END
40 REM REST OF PROGRAM . . .
999 END

In this example, the program asks the user for confirmation before proceeding. If the user responds with "NO", the program ends immediately using the END statement; otherwise, it continues to execute.

EXP

TYPE: Function-Numeric

FORMAT: EXP(<number>)

Action: EXP computes the exponential function of the given number, which is the mathematical constant e (approximately 2.71828183) raised to the power of the number. It is a fundamental function in mathematics, particularly in growth processes, decay processes, and in calculating compound interest. However, care must be taken as providing a value greater than 88.0296919 to the function will result in an ?OVERFLOW error.

EXAMPLES of EXP Function:

10 PRINT EXP(1)
20 X = Y*EXP(Z*Q)

In these examples, EXP(1) calculates the value of e, and EXP(Z*Q) demonstrates how to use the function to compute e raised to the power of the product of Z and Q, showcasing the flexibility and power of the EXP function in mathematical calculations.

FN

TYPE: Function-Numeric

FORMAT: FN<name>(<number>)

Action: FN calls a user-defined function that has been previously established with a DEF FN statement. It calculates the formula associated with the <name>, substituting <number> into the formula's variable slot, and returns a numeric result. User-defined functions are a powerful feature for reusing formulas and simplifying complex calculations within a program. They can be used directly, provided the defining DEF FN statement has been executed beforehand. Attempting to use an FN function before it has been defined with DEF FN results in an "UNDEF'D FUNCTION" error.

EXAMPLES of FN (User-Defined) Function:

PRINT FN A(Q)
1100 J = FN J(7) + FN J(9)
9990 IF FN B7(1+1) = 6 THEN END

In these examples, FN is used to call user-defined functions within expressions, demonstrating how custom functions can be integrated seamlessly into BASIC programming for versatile and dynamic calculations.

FOR...TO...

TYPE: Statement

FORMAT: FOR <variable> = <start> TO <limit> [STEP <increment>]

Action: The FOR statement initiates a loop that runs a specified number of times, automatically incrementing the counter variable from a start value to a limit value, optionally by a specific increment. It is a fundamental control structure for iterating over a block of code multiple times, simplifying programs that require repetitive tasks. The loop is terminated with a NEXT statement, which also specifies the variable being used as the counter. If STEP is omitted, the variable is incremented by 1 by default. This statement streamlines coding by replacing multiple repetitive lines with a concise loop structure.

Example without FOR statement (Counting from 1 to 10):

100 L = 1
110 PRINT L
120 L = L + 1
130 IF L <= 10 THEN 110
140 END

Using the FOR statement (Achieving the same outcome):

100 FOR L = 1 TO 10
110 PRINT L
120 NEXT L
130 END

In these examples, the FOR loop version simplifies the program by reducing the need for manual incrementing and condition checking, showcasing the efficiency and readability improvements offered by using loop constructs in BASIC programming.

FRE

TYPE: Function

FORMAT: FRE(<variable>)

Action: FRE calculates and returns the amount of free RAM available for your program and its variables, helping manage memory usage and prevent the "OUT OF MEMORY" error. The input variable is a placeholder and does not affect the outcome of the function. It's a critical tool for monitoring and optimizing memory utilization, especially in complex programs or those running on hardware with limited resources.

Note: If the result from FRE is negative, you should add 65536 to get the correct number of bytes available in memory. This adjustment accounts for the way the Commodore 64 handles negative numbers in its memory calculations.

EXAMPLES of FRE Function:

PRINT FRE(0)
10 X = (FRE(K) - 1000) / 7
950 IF FRE(0) < 100 THEN PRINT "NOT ENOUGH ROOM"

To always get the current available RAM in bytes:

PRINT FRE(0) - (FRE(0) < 0) * 65536

This formula adjusts for negative values, ensuring the accurate representation of available memory.

GET

TYPE: Statement

FORMAT: GET <variable list>

Action: GET is used to read individual keystrokes from the user, storing each character input into the Commodore 64's keyboard buffer, which can hold up to 10 characters. Subsequent characters beyond the 10th are discarded. The GET statement facilitates interaction with the user by allowing the program to process input as it's entered, rather than waiting for an ENTER key press as with the INPUT statement. It's particularly useful for real-time applications or games where immediate feedback or action is required. To prevent syntax errors when expecting numeric input, it's advisable to initially read inputs as strings and then convert them to numbers.

Note: Utilizing GET can circumvent some limitations associated with the INPUT statement, providing more control over user input handling in a program.

EXAMPLES of GET Statement:

10 GET A$: IF A$ ="" THEN 10 ; REM LOOPS IN LINE 10 UNTIL ANY KEY IS HIT
20 GET A$, B$, C$, D$, E$ ; REM READS 5 KEYS
30 GET A, A$

In these examples, GET is demonstrated as a tool for both looping until a keypress is detected and for gathering multiple keystrokes into variables for processing within a BASIC program.

GET# hashmark

TYPE: I/O Statement

FORMAT: GET# <file number>, <variable list>

Action: GET# reads characters one by one from a specified device or file, similar to the GET statement but sourcing data from external inputs rather than the keyboard. This statement is useful for processing data sequentially from files or devices, allowing for controlled, character-by-character input handling. If no character is available, string variables are set to an empty string (""), and numeric variables are set to 0. Special characters, such as commas or the RETURN key (ASCII code 13), are treated like any other character. When reading from device #3 (the TV screen), GET# reads characters from the screen, advancing the cursor by one position rightward each time it's called, with line-endings marked by CHR$(13).

EXAMPLES of GET# Statement:

5 GET#1, A$
10 OPEN 1,3: GET#1, Z7$
20 GET#1, A, B, C$, D$

In these examples, GET# is used to read data from a file or device, demonstrating how to incorporate external data sources into a BASIC program for dynamic input processing.

GOSUB

TYPE: Statement

FORMAT: GOSUB <line number>

Action: GOSUB directs program execution to a specific subroutine located at the given line number, with a key feature: it remembers the origin point. Upon reaching a RETURN statement within the subroutine, execution returns to the line immediately following the original GOSUB call. Subroutines are highly beneficial for executing repetitive tasks or sequences throughout a program without duplicating code, thereby conserving program space and enhancing maintainability. GOSUB is akin to DEF FN in its space-saving function but applies to multi-line routines rather than single formulas.

Inefficient program without GOSUB:

100 PRINT "THIS PROGRAM PRINTS"
110 FOR L = 1 TO 500:NEXT
120 PRINT "SLOWLY ON THE SCREEN"
130 FOR L = 1 TO 500:NEXT
140 PRINT "USING A SIMPLE LOOP"
150 FOR L = 1 TO 500:NEXT
160 PRINT "AS A TIME DELAY."
170 FOR L = 1 TO 500:NEXT

Efficient use of GOSUB:

100 PRINT "THIS PROGRAM PRINTS"
110 GOSUB 200
120 PRINT "SLOWLY ON THE SCREEN"
130 GOSUB 200
140 PRINT "USING A SIMPLE LOOP"
150 GOSUB 200
160 PRINT "AS A TIME DELAY."
170 GOSUB 200
180 END
200 FOR L = 1 TO 500 NEXT
210 RETURN

In this comparison, the use of GOSUB eliminates the need to repeat the delay loop multiple times, instead calling a single, reusable subroutine that introduces the delay, demonstrating an effective way to streamline BASIC programming.

GOTO

TYPE: Statement

FORMAT: GOTO <line number> or GO TO <line number>

Action: GOTO instructs the BASIC interpreter to jump to a specified line number, changing the normal sequence of program execution. This allows for flexibility in navigating through the program's structure, enabling loops, conditional execution paths, and more dynamic flow control. However, care must be taken to avoid creating infinite loops, such as 10 GOTO 10, unless intentionally designed for a purpose, as these can only be interrupted by user intervention (e.g., pressing the <RUN/STOP> key). GOTO provides a powerful, albeit basic, tool for directing program flow.

EXAMPLES of GOTO Statement:

GOTO 100
10 GO TO 50
20 GOTO 999

In these examples, GOTO is used to direct program execution to different parts of the code, demonstrating its utility in controlling the flow of a BASIC program.

IF...THEN...

TYPE: Statement

FORMAT:

  • IF <expression> THEN <line number>
  • IF <expression> GOTO <line number>
  • IF <expression> THEN <statements>

Action: The IF...THEN... statement is fundamental to adding decision-making capabilities to BASIC programs, allowing for conditional execution based on the evaluation of an expression. The expression can incorporate variables, constants, comparisons, and logical operations. If the expression evaluates to true, the program will either jump to a specified line number or execute the statements provided after THEN. If the expression is false, the program skips the THEN part and continues with the next line in the program, effectively allowing for branching logic and more complex program flows based on dynamic conditions.

EXAMPLE of IF...GOTO...Statement:

100 INPUT "TYPE A NUMBER"; N
110 IF N <= 0 GOTO 200
120 PRINT "SQUARE ROOT=" SQR(N)
130 GOTO 100
200 PRINT "NUMBER MUST BE >0"
210 GOTO 100

EXAMPLE OF IF...THEN...Statement:

100 FOR L = 1 TO 100
110 IF RND(1) < .5 THEN X=X+1: GOTO 130
120 Y=Y+1
130 NEXT L
140 PRINT "HEADS=" X
150 PRINT "TAILS= " Y

These examples illustrate how IF...THEN... statements are used to guide program execution, from simple condition checking to more complex scenarios involving multiple conditions and actions within the same line.

INPUT

TYPE: Statement

FORMAT: INPUT ["<prompt>";] <variable list>

Action: INPUT prompts the user to enter data during program execution, displaying a question mark (?) followed by a blinking cursor where the user can type their response, concluded with the RETURN key. Optionally, a custom prompt can precede the question mark, enhancing user interaction by providing context or instructions. The entered data is then stored in the specified variable(s). Multiple variables can be defined in the variable list to accept several inputs in one statement. INPUT is essential for interactive BASIC programs, allowing dynamic data entry that influences program behavior.

EXAMPLES of INPUT Statement:

100 INPUT A
110 INPUT B, C, D
120 INPUT "PROMPT"; E

In these examples, the INPUT statement is used in its simplest form to request a single piece of data, as well as in more complex scenarios involving multiple data points or custom prompts, demonstrating its versatility in collecting user input.

INPUT# (hashmark)

TYPE: I/O Statement

FORMAT: INPUT# <file number>, <variable list>

Action: INPUT# facilitates the retrieval of data from files stored on disk or tape, offering a streamlined approach compared to the character-by-character method of GET#. For it to function, the target file must first be opened using the OPEN statement. INPUT# reads entire variables at once, recognizing variable terminations upon encountering a RETURN code (CHR$(13)), a comma (,), a semicolon (;), or a colon (:). Special characters can be included in the data by enclosing them in quotes. It is vital to match the variable type to the data format; numeric variables expecting numeric input will trigger a BAD DATA error if non-numeric characters are encountered. Additionally, string variables can hold up to 80 characters, with longer inputs resulting in a STRING TOO LONG error. When applied to device #3 (the screen), INPUT# captures an entire logical line, advancing the cursor to the beginning of the next line.

EXAMPLES of INPUT# Statement:

10 INPUT#1, A
20 INPUT#2, A$, B$

In these examples, INPUT# is employed to efficiently load data into variables from a file, demonstrating its utility in data management within BASIC programs.

INT

TYPE: Integer Function

FORMAT: INT(<numeric>)

Action: INT calculates the integer part of a given numerical expression by truncating the fractional component. For positive numbers, INT simply removes the fraction, whereas for negative numbers, INT returns the next lower integer, effectively rounding down to the nearest integer less than or equal to the expression. This behavior ensures that the function consistently removes the decimal part without rounding to the nearest whole number, which is especially notable in handling negative values.

EXAMPLES of INT Function:

120 PRINT INT(99.4343), INT(-12.34)

In this example, INT(99.4343) evaluates to 99, as the fractional part is discarded. Conversely, INT(-12.34) results in -13 because the function rounds down to the next lower integer, demonstrating INT's straightforward yet crucial role in numerical manipulation within BASIC programs.

LEFT$

TYPE: String Function

FORMAT: LEFT$ (<string>, <integer>)

Action: LEFT$ extracts and returns the leftmost portion of a specified string, up to the number of characters indicated by the integer parameter. The integer must fall within the range of 0 to 255, guiding the length of the substring to be returned. Should the specified integer exceed the original string's length, the entire string is returned. Conversely, specifying an integer value of zero results in a null string, effectively producing an empty string output.

EXAMPLES of LEFT$ Function:

10 A$ = "COMMODORE COMPUTERS"
20 B$ = LEFT$(A$, 9): PRINT B$

RUN

Output: COMMODORE

This example demonstrates using LEFT$ to retrieve and print the first 9 characters of the string stored in A$, showcasing how LEFT$ can be effectively utilized for substring extraction in BASIC programming.

LEN

TYPE: Integer Function

FORMAT: LEN(<string>)

Action: LEN calculates and returns the total number of characters within the specified string expression. This count includes all characters, such as non-printable characters and spaces, ensuring an accurate representation of the string's length. LEN is an essential function for string manipulation tasks, such as parsing, validating input, or dynamically adjusting program behavior based on string content length.

EXAMPLE of LEN Function:

CC$ = "COMMODORE COMPUTER": PRINT LEN(CC$)

Output: 18

In this example, LEN is used to determine the length of the string "COMMODORE COMPUTER", correctly identifying it as 18 characters long. This demonstrates LEN's utility in assessing string lengths for a variety of programming needs.

LET

TYPE: Statement

FORMAT: [LET] <variable> = <expression>

Action: LET is traditionally used in BASIC programming to assign the result of an expression to a variable. However, the keyword LET is optional, as the assignment can be understood directly from the context provided by the equal sign (=). Omitting LET is a common practice among experienced programmers, as it saves memory and reduces clutter without affecting functionality. The use of LET is therefore a matter of style rather than necessity, with the assignment operation itself being crucial for defining or updating variable values within a program.

EXAMPLES of LET Statement:

10 LET D = 12                ; This is the same as D = 12
20 LET E$ = "ABC"
30 F$ = "WORDS"
40 SUM$ = E$ + F$            ; SUM$ would equal ABCWORDS

In these examples, both forms of assignment (with and without LET) are demonstrated, showcasing how BASIC variables can be assigned literal values, string values, or the results of expressions, effectively highlighting the flexibility and ease of variable management in BASIC programming.

LIST

TYPE: Command

FORMAT: LIST [[<first-line>]-[<last-line>]]

Action: The LIST command displays the BASIC program lines stored in the memory of the Commodore 64, making it a vital tool for reviewing and editing your program. You can list the entire program, specific lines, or ranges of lines, providing flexibility in how you view your code. This capability, combined with the C64's screen editor, facilitates efficient program development and debugging directly on the machine.

EXAMPLES of LIST Command:

  • LIST - Lists the entire program currently in memory.
  • LIST 500 - Lists only line 500.
  • LIST 150- - Lists from line 150 to the end of the program.
  • LIST -1000 - Lists from the beginning of the program up through line 1000.
  • LIST 150-1000 - Lists lines 150 through 1000, inclusive.
  • 10 PRINT "THIS IS LINE 10"
  • 20 LIST - Demonstrates LIST being used within program execution to list the program itself.
  • 30 PRINT "THIS IS LINE 30"

These examples illustrate the versatility of the LIST command in accessing different parts of a BASIC program for review or editing, showcasing its essential role in the programming workflow on the Commodore 64.

LOAD

TYPE: Command

FORMAT: LOAD ["<file-name>"] [, <device>] [, <address>]

Action: LOAD transfers the contents of a program file from a tape or disk into the computer's memory, making it available for execution or editing. By default, if no device number is specified, the computer will assume the cassette unit (device 1). The disk drive, commonly used, is device number 8. Utilizing LOAD automatically closes any open files and, when issued in direct mode, initiates a CLR (clear) operation to prepare memory for the new program. If executed within a program, LOAD triggers the automatic execution (RUN) of the loaded program, facilitating the chaining of multiple programs. Notably, variable values are preserved during chaining, allowing seamless data transfer between programs.

EXAMPLES of LOAD Command:

  • LOAD - Reads and loads the next program found on tape.
  • LOAD A$ - Loads a program from tape or disk using the file name stored in variable A$.
  • LOAD "*", 8 - Loads the first program found on a disk in device 8.
  • LOAD "", 1, 1 - Loads the first program on tape into its original memory location.
  • LOAD "STAR TREK" followed by "PRESS PLAY ON TAPE" - Loads a specific file named "STAR TREK" from tape.
  • LOAD "FUN", 8 - Loads a file named "FUN" from the disk.
  • LOAD "GAME ONE", 8, 1 - Loads a file named "GAME ONE" from disk into a specific memory location.

These examples demonstrate the versatility and utility of the LOAD command in managing program files and memory on the Commodore 64, essential for both programming and game playing.

LOG

TYPE: Floating-Point Function

FORMAT: LOG(<numeric>)

Action: LOG computes the natural logarithm (ln) of its argument, which is the logarithm to the base e (approximately 2.71828183). This function is crucial in various fields of mathematics, science, and engineering for analyzing exponential growth, decay rates, and in algorithms requiring logarithmic calculations. It's important to note that LOG is defined only for positive arguments; attempting to calculate the logarithm of zero or a negative number results in an ?ILLEGAL QUANTITY error in BASIC.

EXAMPLES of LOG Function:

25 PRINT LOG(45/7)

Output: 1.86075234

10 NUM = LOG(ARG) / LOG(10)  ; Calculates the LOG of ARG to the base 10

In these examples, LOG is used to perform natural logarithm calculations, including converting a natural log to a log of base 10 by dividing by LOG(10), demonstrating the versatility of LOG in mathematical operations.

MID$

TYPE: String Function

FORMAT: MID$(<string>, <numeric-1> [, <numeric-2>])

Action: MID$ extracts a specified segment, or substring, from a given string. The start position of this segment within the original string is determined by <numeric-1>, while its length is specified by <numeric-2>. If <numeric-2> is omitted, the substring extends from the start position to the end of the string. If <numeric-1> exceeds the string's length, or if <numeric-2> is zero, MID$ returns an empty string. This function is invaluable for parsing and manipulating strings, enabling precise control over which parts of a string are accessed or modified.

EXAMPLE of MID$ Function:

10 A$ = "GOOD"
20 B$ = "MORNING EVENING AFTERNOON"
30 PRINT A$ + MID$(B$, 8, 8)

Output: GOOD EVENING

In this example, MID$ is used to extract "EVENING" from the string stored in B$, starting from the 8th character for a length of 8 characters, demonstrating how MID$ facilitates substring retrieval within BASIC programming.

NEW

TYPE: Command

FORMAT: NEW

Action: NEW clears the current program from memory along with all defined variables, essentially resetting the programming environment to a clean state. It's typically used in direct mode as a preliminary step before entering a new program to ensure that the workspace is free from residual data or code that could interfere with the new development. While it can be executed within a program, caution is advised since it irreversibly removes all existing code and data in memory, potentially disrupting debugging efforts or leading to data loss if used unintentionally.

BE CAREFUL: Starting to input a new program without first executing NEW can lead to unintended mixing of old and new code, resulting in confusing and erroneous program behavior.

EXAMPLES of NEW Command:

  • NEW - Completely clears the current program and all variables from memory.
  • 10 NEW - Includes a NEW operation within a program, which will clear all memory contents and halt further execution.

These examples highlight the use of NEW for memory management and preparation for new program development on the Commodore 64.

NEXT

TYPE: Statement

FORMAT: NEXT [<counter>] [, <counter>]...

Action: NEXT is employed in conjunction with FOR to delineate the conclusion of a FOR...NEXT loop. Although NEXT may not physically appear as the final statement within the loop's body, it signifies the loop's logical end. It increments the loop counter(s) specified after FOR, and checks if the loop should continue or terminate based on the counter's value relative to the loop's terminal condition. NEXT supports ending multiple nested loops simultaneously by listing the loop counters in reverse nesting order, from the most deeply nested to the least. It's important to note that loops can be nested up to 9 levels deep. Omitting the counter variable(s) in a NEXT statement causes the loop counter for the current loop level to be incremented. This design allows for concise and flexible loop control within BASIC programming.

EXAMPLES of NEXT Statement:

10 FOR J = 1 TO 5: FOR K = 10 TO 20: FOR N = 5 TO -5 STEP -1
20 NEXT N, K, J            ; Stopping Nested Loops
10 FOR L = 1 TO 100
20 FOR M = 1 TO 10
30 NEXT M
400 NEXT L                 ; Note how the loops do NOT cross each other
10 FOR A = 1 TO 10
20 FOR B = 1 TO 20
30 NEXT
40 NEXT                    ; Notice that no variable names are needed

These examples illustrate the versatility of the NEXT statement in managing loop execution, from basic single loops to complex nested loops, demonstrating the foundational role of FOR...NEXT loops in structured BASIC programming.

NOT

TYPE: Logical Operator

FORMAT: NOT <expression>

Action: NOT is a logical operator that inverts the binary representation of its operand, producing a two's complement result. This means that each bit of the operand is flipped: 0 becomes 1, and 1 becomes 0. When applied to floating-point numbers, they are first converted to integers, discarding any fractional part. NOT can also invert the truth value of an expression in logical comparisons, effectively reversing the comparison's outcome. It is a powerful tool for bitwise manipulation and logical decision-making within a program, allowing for nuanced control over conditions and binary data operations.

EXAMPLES of NOT Operator:

10 IF NOT AA = BB AND NOT (BB = CC) THEN...

This line demonstrates using NOT to reverse the truth value of expressions, impacting the flow of decision-making based on the specified conditions.

NN% = NOT 96: PRINT NN%

Output: -97

In this example, NOT is applied to the integer 96, flipping its bits and printing the two's complement result, -97, illustrating the operator's effect on integer values.

ON

TYPE: Statement

FORMAT: ON <variable> GOTO / GOSUB <line-number> [, <line-number>]...

Action: ON allows for conditional branching to one of several specified line numbers based on the integer value of a given variable. This statement simplifies decision-making processes in a program by replacing multiple IF...THEN... statements with a single, more efficient structure. The targeted line number corresponds to the integer value of the variable: a variable value of 1 jumps to the first line number listed, a value of 2 to the second, and so on. Non-integer values have their fractional parts ignored. The statement is ignored if the variable's value is zero, negative, or exceeds the number of line numbers provided, continuing execution with the subsequent line.

EXAMPLES of ON Statement:

ON -(A=7)-2*(A=3)-3*(A<3)-4*(A>7) GOTO 400, 900, 1000, 100
ON X GOTO 100, 130, 180, 220
ON X+3 GOSUB 9000, 20, 9000
100 ON NUM GOTO 150, 300, 320, 390
500 ON SUM/2 + 1 GOSUB 50, 80, 20

These examples demonstrate the ON statement's flexibility in directing program flow, enabling concise and readable conditional branching without the clutter of numerous IF statements. Whether for GOTO or GOSUB operations, ON serves as a compact, versatile tool for navigating through different program segments based on variable conditions.

OPEN

TYPE: I/O Statement

FORMAT: OPEN <file-num>, [<device>] [, <address>] [, "<File-name> [, <type>] [, <mode>]"]

Action: OPEN is used to establish a communication channel with a peripheral device for data input and/or output. The complexity of the OPEN statement can vary depending on the device and the nature of the operation, but at its simplest, it requires a logical file number and a device number. The statement sets up the necessary parameters for file operations, including the type of access (sequential, random, etc.), the mode (read, write, append), and other device-specific settings.

EXAMPLES of OPEN Statements:

  • 10 OPEN 2, 8, 4, "DISK-OUTPUT,SEQ,W" - Opens a sequential file on a disk for writing.
  • 10 OPEN 1, 1, 2, "TAPE-WRITE" - Prepares to write an End-of-File marker on tape upon closing.
  • 10 OPEN 50, 0 - Opens the keyboard for input.
  • 10 OPEN 12, 3 - Opens the screen for output.
  • 10 OPEN 130, 4 - Opens the printer for output.
  • 10 OPEN 1, 1, 0, "NAME" - Opens a file named "NAME" for reading from the cassette.
  • 10 OPEN 1, 1, 1, "NAME" - Opens a file named "NAME" for writing to the cassette.
  • 10 OPEN 1, 2, 0, CHR$(10) - Opens a channel to an RS-232 device.
  • 10 OPEN 1, 4, 0, "STRING" - Sends uppercase/graphics to the printer.
  • 10 OPEN 1, 4, 7, "STRING" - Sends upper/lowercase to the printer.
  • 10 OPEN 1, 5, 7, "STRING" - Similar to the previous command, but with device #5.
  • 10 OPEN 1, 8, 15, "COMMAND" - Sends a command to the disk.

These examples showcase the versatility of the OPEN statement in handling a wide range of input and output operations across different devices, forming the basis of file and device management in BASIC programming.

OR

TYPE: Logical Operator

FORMAT: <operand> OR <operand>

Action: The OR operator is utilized in both relational operations and bitwise calculations. In relational contexts, it combines two or more conditions, yielding a true result (-1 in BASIC) if at least one of the conditions evaluates to true. This facilitates complex decision-making within program flow by allowing multiple criteria to influence the outcome. For bitwise operations, OR compares each bit of its operands and sets the corresponding bit in the result to 1 if either or both of the bits in the operands are 1. This behavior enables the manipulation of data at the binary level, providing a means to combine flags, set specific bits, or perform other bitwise transformations. Operands are treated as 16-bit, two's complement integers, and must fall within the valid range to avoid errors.

EXAMPLES of OR Operator:

100 IF (AA = BB) OR (XX = 20) THEN...

This line demonstrates the use of OR in a conditional statement, evaluating to true if either AA equals BB or XX equals 20.

230 KK% = 64 OR 32: PRINT KK%

Output: 96

In this example, the OR operator combines the binary representations of 64 (1000000) and 32 (0100000), resulting in 1100000 or 96 in decimal, illustrating OR's application in bitwise logic operations.

PEEK

TYPE: Integer Function

FORMAT: PEEK(<numeric>)

Action: PEEK retrieves the value from a specified memory location, returning an integer between 0 and 255 that represents the contents of that memory address. The memory location to be read is determined by the <numeric> expression, which must fall within the valid address range of 0 to 65535. Attempting to PEEK outside this range results in an ?ILLEGAL QUANTITY error. PEEK is instrumental in directly accessing and manipulating the Commodore 64's memory, allowing for a wide range of advanced programming techniques, including custom graphics handling, device control, and direct interaction with the system's hardware components.

EXAMPLES of PEEK Function:

10 PRINT PEEK(53280) AND 15  ; Returns the value of the screen border color.

This example uses PEEK to obtain the current border color of the screen by reading the corresponding memory location.

5 A% = PEEK(45) + PEEK(46) * 256  ; Calculates the starting address of the BASIC variable table.

Here, PEEK reads two memory locations to construct the address of the BASIC variable table, demonstrating how PEEK can be used to access system information and memory structures.

POKE

TYPE: Statement

FORMAT: POKE <location>, <value>

Action: POKE directly modifies the content of a specified memory location or input/output register by writing a single-byte (8-bit) binary value into it. The <location> must be a valid memory address within the 0 to 65535 range, while <value> should be an integer between 0 and 255. Utilizing POKE improperly, especially with values outside these ranges, will result in an ?ILLEGAL QUANTITY error. POKE, alongside PEEK, empowers programmers to directly manipulate data storage, control device hardware for graphics and sound, interface with assembly language routines, and adjust operating system parameters. These capabilities make POKE a powerful tool for customizing and optimizing system behavior far beyond BASIC's standard functionalities.

EXAMPLES of POKE Statement:

  • POKE 1024, 1 - Displays an "A" in the first position of the screen, assuming a standard Commodore 64 character set.
  • POKE 2040, PTR - Sets the sprite pointer for Sprite #0 to the value stored in PTR.
  • 10 POKE RED, 32 - This could be setting a color value, assuming RED is a memory location controlling some color property.
  • 20 POKE 36879, 8 - Might be manipulating a hardware register for specific device behavior.
  • 2050 POKE A, B - A generic example of using POKE to write the value B into the memory location A.

These examples underscore the versatility and depth POKE adds to Commodore 64 programming, enabling direct hardware access and memory manipulation.

POS

TYPE: Integer Function

FORMAT: POS(<dummy>)

Action: POS is utilized to ascertain the current cursor position within the logical line of the screen, with values ranging from 0 (for the leftmost position) to 79 (for the rightmost position on an 80-character logical line). On the Commodore 64, which features a 40-column display, positions numbered from 40 to 79 correspond to locations on a conceptual second line. The argument passed to POS is a placeholder and has no impact on the function's outcome. This capability is especially useful for managing text output and ensuring that content is appropriately aligned or wrapped on the screen.

EXAMPLE of POS Function:

1000 IF POS(0) > 38 THEN PRINT CHR$(13)

In this example, the POS function is employed to check if the cursor has reached beyond the 38th position on the screen. If so, a carriage return (CHR$(13)) is printed, moving the cursor to the beginning of the next line, demonstrating how POS can be leveraged to control text layout dynamically.

PRINT

TYPE: Statement

FORMAT: PRINT [<variable>][<,/;><variable>]...

Action: PRINT is primarily utilized for displaying data on the screen, though its output can be redirected to other devices using the CMD statement. It supports expressions of any type as arguments. If no arguments are provided, PRINT outputs a blank line. The format of the output can be controlled using commas (,), semicolons (;), or spaces, affecting how subsequent values are displayed:

  • A comma moves the cursor to the start of the next 10-character print zone on an 80-character logical line, dividing the line into 8 zones.
  • A semicolon prints the next item directly after the previous, with numeric items being followed by a space, and positive numbers preceded by one.
  • Omitting punctuation or using spaces between items functions like a semicolon, but using spaces between numeric items or a string and a numeric item without punctuation stops the output.

Ending a PRINT statement with a comma or semicolon allows the next PRINT statement to continue on the same line, otherwise, a newline is automatically added. On a 40-column screen, if the printed data exceeds the line width, it continues onto the next line.

EXAMPLES of PRINT Statement:

1) Demonstrates various arithmetic operations and the spacing between printed results.

5 X = 5
10 PRINT -5*X, X-5, X+5, X^5

Output: -25 0 10 3125

2) Shows concatenation of strings and variables, with output spanning multiple PRINT statements.

5 X = 9
10 PRINT X; "SQUARED IS"; X*X; "AND";
20 PRINT X "CUBED IS" X^3

Output: 9 SQUARED IS 81 AND 9 CUBED IS 729

These examples highlight the flexibility of the PRINT statement in formatting and displaying data, essential for interactive BASIC programs.

TYPE: I/O Statement

FORMAT: PRINT#<file-number>[<variable>][<,/;><variable>]...

Action: PRINT# directs data output to a logical file rather than the screen, using the file number assigned during the file's OPEN operation. It can handle expressions of any type and uses punctuation (blanks, commas, semicolons) to format the output, similar to the PRINT statement. However, with PRINT#, punctuation mainly influences how data is separated, especially in tape files where spacing by print zones is not applicable. Instead, data is written as a continuous stream of characters, with numeric items followed and, if positive, preceded by a space. Ending the output list with a comma or semicolon suppresses the automatic carriage-return and line-feed, affecting how subsequent PRINT# outputs are formatted. This behavior is crucial for writing data files where precise control over format and data separation is necessary.

EXAMPLES of PRINT# Statement:

1) Demonstrates writing multiple data items to a tape file, using CHR$(13) to insert carriage returns between items.

10 OPEN 1, 1, 1, "TAPE FILE"
20 R$ = CHR$(13)
30 PRINT#1, 1; R$; 2; R$; 3; R$; 4; R$; 5
40 PRINT#1, 6
50 PRINT#1, 7

2) Shows how to use custom separators (CHR$(44) for commas) and suppress line feeds with CHR$(13).

10 CO$ = CHR$(44): CR$ = CHR$(13)
20 PRINT#1, "AAA" CO$ "BBB", "CCC"; "DDD"; "EEE" CR$ "FFF" CR$;
30 INPUT#1, A$, BCDE$, F$

3) Illustrates suppressing line feeds between strings and the impact on subsequent INPUT# statements.

5 CR$ = CHR$(13)
10 PRINT#2, "AAA"; CR$; "BBB"
20 PRINT#2, "CCC";
30 INPUT#2, A$, B$, DUMMY$, C$

These examples highlight how PRINT# is utilized for controlled data output to files, facilitating complex file creation and manipulation tasks in BASIC programming.

READ

TYPE: Statement

FORMAT: READ <variable>[, <variable>]...

Action: READ retrieves values from DATA statements within a program and assigns them to specified variables in the order they appear. It facilitates the separation of data from logic, allowing for easier management and reuse of static values. Variables must match the type of data they are assigned, or a ?SYNTAX ERROR occurs, with the error referencing the DATA statement's line number, not the READ line. If READ attempts to access more data elements than are available, a ?OUT OF DATA error is triggered. Conversely, if not all data elements are consumed by READ statements, subsequent READs continue from the last accessed element, demonstrating the sequential nature of data access. RESTORE can be used to reset the read pointer to a specific DATA statement.

EXAMPLES of READ Statement:

110 READ A, B, C$
120 DATA 1, 2, "HELLO"

Demonstrates reading multiple types of data into variables of corresponding types.

100 FOR X = 1 TO 10: READ A(X): NEXT
200 DATA 3.08, 5.19, 3.12, 3.98, 4.24
210 DATA 5.08, 5.55, 4.00, 3.16, 3.37

Fills an array with values from DATA statements, illustrating how READ sequences through DATA.

1 READ CITY$, STATE$, ZIP
5 DATA "DENVER", "COLORADO", 80211

Shows READ pulling a set of related information into distinct variables, highlighting its use for organizing and accessing structured data.

These examples underscore READ's utility in BASIC programming for efficiently managing and accessing predefined data sets.

REM

TYPE: Statement

FORMAT: REM [<remark>]

Action: The REM (remark) statement is a tool for incorporating comments or notes within a BASIC program, serving to clarify the purpose, functionality, or any other noteworthy details about the code. These comments are invaluable for making the code more readable and maintainable, both for the original author and others who may work with the code in the future. Despite being ignored during program execution, REM statements are displayed as written when the program is listed, assisting in understanding the program's flow and logic. REM statements can also serve as placeholders or labels within the code, which can be targeted by GOTO or GOSUB statements, with program execution then proceeding to the next executable line.

EXAMPLES of REM Statement:

10 REM CALCULATE AVERAGE VELOCITY
20 FOR X = 1 TO 20 :REM LOOP FOR TWENTY VALUES
30 SUM = SUM + VEL(X): NEXT
40 AVG = SUM/20

In these examples, REM statements provide clear descriptions of what specific sections of the program are intended to do, such as calculating an average velocity or iterating through a loop for a specified number of values, demonstrating the significance of including comments for enhancing the understandability of BASIC programs.

RESTORE

TYPE: Statement

FORMAT: RESTORE

Action: RESTORE is used to reset BASIC's internal pointer back to the first DATA statement in a program. This allows previously READ data to be re-read from the beginning, facilitating repeated use of static data within different parts of the program without duplicating DATA statements. RESTORE can be particularly useful in loops or when initializing multiple data structures with the same set of values. By resetting the data pointer, RESTORE ensures that subsequent READ statements will start accessing data from the first DATA statement encountered in the program's source code.

EXAMPLES of RESTORE Statement:

100 FOR X = 1 TO 10: READ A(X): NEXT
200 RESTORE
300 FOR Y = 1 TO 10: READ B(Y): NEXT

4000 DATA 3.08, 5.19, 3.12, 3.98, 4.24
4100 DATA 5.08, 5.55, 4.00, 3.16, 3.37

This example demonstrates using RESTORE to refill two arrays with identical data from the same set of DATA statements.

10 DATA 1, 2, 3, 4
20 DATA 5, 6, 7, 8
30 FOR L = 1 TO 8
40 READ A: PRINT A
50 NEXT
60 RESTORE
70 FOR L = 1 TO 8
80 READ A: PRINT A
90 NEXT

In this sequence, RESTORE is employed after the first complete reading of the DATA, allowing the program to re-read and print the same data values again, showcasing RESTORE's utility in managing and reusing static data within BASIC programs.

RETURN

TYPE: Statement

FORMAT: RETURN

Action: RETURN signals the end of a subroutine initiated by a GOSUB statement, allowing the program to resume execution from the point immediately following the original GOSUB call. This mechanism supports the structured use of subroutines, enabling code reuse and improving program organization. For nested subroutines, each GOSUB must correspond to a RETURN to ensure proper exit and continuation of the program flow. While a subroutine may contain multiple RETURN statements, execution will cease and return to the calling point upon reaching the first RETURN encountered.

EXAMPLE of RETURN Statement:

10 PRINT "THIS IS THE PROGRAM"
20 GOSUB 1000
30 PRINT "PROGRAM CONTINUES"
40 GOSUB 1000
50 PRINT "MORE PROGRAM"
60 END
1000 PRINT "THIS IS THE GOSUB": RETURN

In this example, the GOSUB statement at lines 20 and 40 calls a subroutine starting at line 1000, which prints a message and then uses RETURN to exit back to the next line of the main program flow, demonstrating how RETURN integrates into subroutine management for concise and readable BASIC programming.

TYPE: String Function

FORMAT: RIGHT$ (<string>, <numeric>)

Action: RIGHT$ extracts a substring from the specified string, starting from the right end. The length of this substring is determined by the <numeric> argument, which should be an integer from 0 to 255. If <numeric> is set to zero, RIGHT$ returns an empty string (""). However, if <numeric> exceeds the length of <string>, the function returns the entire string. This function is particularly useful for parsing strings, handling file extensions, or extracting specific segments from textual data based on their position from the end of the string.

EXAMPLE of RIGHT$ Function:

10 MSG$ = "COMMODORE COMPUTERS"
20 PRINT RIGHT$(MSG$, 9)

RUN

Output: COMPUTERS

In this example, RIGHT$ is utilized to retrieve the last 9 characters from the string stored in MSG$, effectively isolating "COMPUTERS" from the original string, showcasing the utility of RIGHT$ in string manipulation within BASIC programs.

RND

TYPE: Floating-Point Function

FORMAT: RND(<numeric>)

Action: RND generates a pseudorandom floating-point number in the range of 0.0 to 1.0. The sequence of random numbers produced depends on the seed value, which is initialized upon system startup. The function's behavior varies based on the sign of the <numeric> argument:

  • A positive <numeric> generates a consistent sequence of pseudorandom numbers from the same seed, allowing for reproducible results which are beneficial for testing.
  • A <numeric> of zero causes RND to produce a number based on the system's "jiffy clock," providing a more unpredictable result.
  • Negative <numeric> values re-seed the random number generator each time, ensuring a fresh sequence of numbers for each call.

EXAMPLES of RND Function:

220 PRINT INT(RND(0) * 50)  ; Generates random integers between 0 and 49.
100 X = INT(RND(1) * 6) + INT(RND(1) * 6) + 2  ; Simulates rolling two dice.
100 X = INT(RND(1) * 1000) + 1  ; Produces random integers between 1 and 1000.
100 X = INT(RND(1) * 150) + 100  ; Yields random numbers in the range of 100 to 249.
100 X = RND(1) * (U - L) + L  ; Generates random numbers within specified upper (U) and lower (L) limits.

These examples demonstrate RND's versatility in creating random numbers for various applications, from simulating dice rolls to generating numbers within a defined range, highlighting its utility in BASIC programming.

RUN

TYPE: Command

FORMAT: RUN [<line-number>]

Action: RUN initiates the execution of the program currently loaded in memory. By default, without specifying a <line-number>, RUN starts from the very first line of the program. If a specific <line-number> is provided, execution begins at that line, enabling targeted program runs or testing of specific sections. An implicit CLR operation clears all variables and resets the system before the program starts, ensuring a clean execution environment. This CLR step can be bypassed with commands like CONT or GOTO for program restarts without losing variable values. Execution ends upon reaching an END or STOP statement, completing the last program line, or encountering an execution error.

EXAMPLES of RUN Command:

  • RUN - Executes the program from the start.
  • RUN 500 - Begins execution at line number 500.
  • RUN X - Attempts to start the program at the line number stored in variable X, leading to an UNDEF'D STATEMENT error if no such line exists.

These examples showcase how the RUN command is used to start or restart a BASIC program, highlighting its flexibility in controlling program execution flow.

SAVE

TYPE: Command

FORMAT: SAVE ["<file-name>"] [, <device-number>] [, <address>]

Action: SAVE writes the currently loaded program in memory to a tape or diskette file, facilitating data preservation and program distribution. The program type is automatically set as "prg" (program). By default, without specifying a device number, the Commodore 64 targets the cassette tape (device 1) for saving. Specifying device number 8 directs the save operation to a disk. The operation does not remove the program from memory, allowing further editing or operations post-SAVE. The SAVE command can be integrated into program logic, resuming execution with the subsequent line upon completion.

EXAMPLES of SAVE Command:

  • SAVE - Saves the current program to tape without specifying a file name.
  • SAVE "ALPHA", 1 - Saves the program under the name "ALPHA" to cassette tape.
  • SAVE "ALPHA", 1, 2 - Saves "ALPHA" to tape, adding an end-of-tape marker.
  • SAVE "FUN.DISK", 8 - Writes the program to disk with the filename "FUN.DISK".
  • SAVE A$ - Saves the program to tape using the filename stored in variable A$.
  • 10 SAVE "HI" - Incorporates a SAVE operation within the program, continuing to the next line afterward.
  • SAVE "ME", 1, 3 - Saves to tape as "ME", ensuring it's stored at the same memory location and concludes with an end-of-tape marker.

These examples demonstrate the versatility and functionality of the SAVE command, from basic saving operations to more complex uses involving program flow integration and specific device targeting.

SGN

TYPE: Integer Function

FORMAT: SGN(<numeric>)

Action: SGN evaluates the sign of the provided numeric argument and returns an integer value based on that sign: 1 for positive numbers, 0 for zero, and -1 for negative numbers. This function is particularly useful in conditional logic and control structures where the sign of a variable influences program flow or decision-making.

EXAMPLE of SGN Function:

90 ON SGN(DV) + 2 GOTO 100, 200, 300

In this example, SGN is used within a conditional jump statement. Depending on the sign of DV, the program will jump to line 100 if DV is negative, to line 200 if DV is zero, or to line 300 if DV is positive. This showcases how SGN can simplify handling different cases based on the numeric sign in BASIC programming.

SIN

TYPE: Floating-Point Function

FORMAT: SIN(<numeric>)

Action: SIN calculates the sine of the provided argument, which must be expressed in radians. This function is essential in trigonometry, physics, engineering, and other fields that require mathematical computations involving angles. The relationship between sine and cosine functions is highlighted by the fact that COS(X) is equivalent to SIN(X + π/2), demonstrating the periodic and phase-shift properties of these trigonometric functions.

EXAMPLE of SIN Function:

235 AA = SIN(1.5): PRINT AA

Output: 0.997494987

In this example, SIN is used to compute the sine of 1.5 radians, demonstrating how to use the function for trigonometric calculations within a BASIC program. The result, approximately 0.997494987, shows the precise computational capabilities of the SIN function in returning the sine of an angle.

SPC

TYPE: String Function

FORMAT: SPC(<numeric>)

Action: SPC generates a string consisting of spaces, the number of which is specified by the <numeric> argument. This function is instrumental in formatting output for both screen display and file writing by inserting the designated number of spaces at the current cursor position. It facilitates the creation of tabulated data, aligns text, and enhances readability in output. The acceptable range for <numeric> is 0 to 255 for screen or tape files, and up to 254 for disk files. When used with printer files, printing a space in the last character position of a line triggers an automatic carriage return and line feed, though no additional spaces are printed on the new line.

EXAMPLE of SPC Function:

10 PRINT "RIGHT "; "HERE &";
20 PRINT SPC(5) "OVER" SPC(14) "THERE"

RUN

Output: RIGHT HERE & OVER THERE

In this example, SPC is utilized to create visual separation between words in printed output, illustrating its utility in achieving specific layout goals within BASIC programming.

SQR

TYPE: Floating-Point Function

FORMAT: SQR(<numeric>)

Action: SQR calculates the square root of its numeric argument, returning the square root value as a floating-point number. This function is essential in mathematics, science, engineering, and any domain requiring geometric, algebraic, or statistical calculations. The numeric argument to SQR must be non-negative, as square roots of negative numbers are not defined within the realm of real numbers, and attempting to compute one results in a ?ILLEGAL QUANTITY error.

EXAMPLE of SQR Function:

FOR J = 2 TO 5: PRINT J*5, SQR(J*5): NEXT

This loop calculates and prints the square root of multiples of 5, from 10 to 25, demonstrating the use of SQR in processing and displaying mathematical computations within a BASIC program.

STATUS

TYPE: Integer Function

FORMAT: STATUS

Action: STATUS returns the outcome of the last input/output operation executed on an open file or peripheral device. It's a critical tool for error handling and operational feedback in programs that interact with external devices such as tapes, disks, printers, and RS-232 interfaces. The value returned by STATUS is a system-defined variable (also referred to as ST) that the KERNAL updates following each I/O operation. This variable encapsulates various STATUS codes as bit flags, each representing different conditions or errors encountered during the operation.

STATUS Code Values Overview:

  • Bit 0 (Value 1): Time out on write (Serial Bus R/W).
  • Bit 1 (Value 2): Time out on read (Serial Bus R/W).
  • Bit 2 (Value 4): Short block (Cassette Read/Tape Verify + Load).
  • Bit 3 (Value 8): Long block (Cassette Read/Tape Verify + Load).
  • Bit 4 (Value 16): Unrecoverable read error (Cassette Read) or any mismatch (Tape Verify + Load).
  • Bit 5 (Value 32): Checksum error (Cassette Read/Tape Verify + Load).
  • Bit 6 (Value 64): End of file (EOI) or end of tape (Cassette Read/Tape Verify + Load).
  • Bit 7 (Value -128): End of tape or device not present (Serial Bus).

These STATUS codes provide detailed feedback on the result of I/O operations, enabling programs to respond appropriately to various conditions or errors, such as handling file end conditions, detecting device presence, and recovering from transmission errors.

Example Usage of STATUS:

To check for a read timeout error on the serial bus:

IF STATUS AND 2 THEN PRINT "Read timeout error."

This illustrates how STATUS can be leveraged to diagnose and handle specific I/O conditions in Commodore 64 programming.

STEP

TYPE: Statement

FORMAT: [STEP <expression>] (within a FOR loop)

Action: STEP is an optional component of a FOR loop that specifies the increment (or decrement) value by which the loop's counter variable should be adjusted on each iteration. The default increment is +1 if STEP is omitted. A STEP value of zero would result in an infinite loop since the counter would never change. The specified STEP value remains constant throughout the loop's duration and cannot be modified once the loop begins. By utilizing different STEP values, programmers can customize the progression of loop counters to suit various needs, whether counting up, down, or in more complex increments.

NOTE: The STEP value is immutable once established within the loop context.

EXAMPLES of STEP Statement:

25 FOR XX = 2 TO 20 STEP 2  ; Loops ten times, with XX taking even values from 2 to 20.
35 FOR ZZ = 0 TO -20 STEP -2  ; Loops eleven times, with ZZ decreasing by 2 on each iteration, from 0 to -20.

These examples demonstrate how STEP influences loop execution, enabling both straightforward counting sequences and more intricate iteration patterns within BASIC programming structures.

STOP

TYPE: Statement

FORMAT: STOP

Action: STOP immediately terminates the execution of a program, shifting control back to direct mode, similar to manually pressing the <RUN/STOP> key. Upon execution, BASIC outputs the message ?BREAK IN LINE nnnnn, with "nnnnn" indicating the line number where the program was halted. All open files remain accessible, and variables retain their values, allowing for post-stop inspection and debugging. The program can be resumed from a specific point using the CONT or GOTO statements, facilitating convenient breakpoints for testing or debugging purposes.

EXAMPLES of STOP Statement:

10 INPUT#1, AA, BB, CC
20 IF AA = BB AND BB = CC THEN STOP
30 STOP
  • If variables AA, BB, and CC are equal, execution stops at line 20, displaying ?BREAK IN LINE 20.
  • For any execution reaching line 30, ?BREAK IN LINE 30 is displayed, demonstrating how STOP can be strategically placed to debug or manage program flow effectively.

STR$

TYPE: String Function

FORMAT: STR$ (<numeric>)

Action: STR$ converts a numeric value into its string representation. This function is particularly useful when concatenating numbers with text or when a numeric value needs to be inserted into a text-based context, such as building a message or outputting data in a specific format. The resulting string includes formatting characteristics inherent to BASIC's handling of numbers: a leading space for positive numbers and a trailing space, ensuring consistent spacing in concatenated strings.

EXAMPLE of STR$ Function:

100 FLT = 1.5E4: ALPHA$ = STR$(FLT)
110 PRINT FLT, ALPHA$

Output: 15000 " 15000 "

This example illustrates the use of STR$ to convert a floating-point number, 1.5E4 (or 15000), into a string. The printed output demonstrates the string representation of the number, including the formatting spaces, alongside the original numeric value, showcasing STR$'s utility in converting and handling numeric data within string contexts.

SYS

TYPE: Statement

FORMAT: SYS <memory-location>

Action: SYS enables a BASIC program to invoke a machine language (ML) subroutine residing at a specified memory location. This capability allows for the integration of high-speed ML routines into BASIC programs, expanding their functionality beyond the limitations of interpreted BASIC code. The <memory-location> argument specifies the starting point of the ML code in either RAM or ROM. For proper return to BASIC after executing the ML subroutine, the ML code must conclude with an RTS (ReTurn from Subroutine) instruction. SYS can be used in both direct mode, for immediate execution, and within a program, to enhance performance or access system features not available in BASIC.

EXAMPLES of SYS Statement:

  • SYS 64738 - Initiates a system cold start by jumping to the corresponding ROM location.

  • 10 POKE 4400, 96: SYS 4400 - Demonstrates injecting a simple machine language instruction (RTS, represented by decimal 96) into RAM at location 4400 and executing it via SYS, illustrating how SYS bridges BASIC and ML programming.

These examples showcase the practical use of SYS for direct machine language program execution within BASIC, providing a powerful tool for advanced programming tasks on the Commodore 64.

TAB

TYPE: String Function

FORMAT: TAB(<numeric>)

Action: TAB adjusts the cursor's position on the screen to the column specified by the <numeric> argument, with the count starting from the left-most position of the current line. This function is designed to be used exclusively with the PRINT statement for output formatting, allowing for aligned text displays on the screen. The numeric range for the argument spans from 0 to 255, enabling positioning across a wide range of columns. TAB's functionality is particularly useful in creating tabulated data or aligning output in a visually structured manner, enhancing readability and presentation of information.

NOTE: TAB has no effect when used in conjunction with PRINT# for writing to logical files, as its purpose is specifically for screen output formatting.

EXAMPLE of TAB Function:

100 PRINT "NAME" TAB(25) "AMOUNT": PRINT
110 INPUT#1, NAM$, AMT$
120 PRINT NAM$ TAB(25) AMT$

Output:

NAME                         AMOUNT

G.T. JONES                   25

This example demonstrates using TAB to align column headings and corresponding data entries, showing how TAB contributes to creating organized and easy-to-read screen outputs in BASIC programming.

TAN

TYPE: Floating-Point Function

FORMAT: TAN(<numeric>)

Action: TAN computes the tangent of the provided numeric expression, which must be in radians. This trigonometric function is fundamental in various mathematical, scientific, and engineering calculations, facilitating the analysis and modeling of periodic phenomena, among other applications. TAN may result in a division by zero error for certain arguments where the cosine of the angle is zero, reflecting the mathematical property that tangent is undefined at these points.

EXAMPLE of TAN Function:

10 XX = .785398163: YY = TAN(XX): PRINT YY

Output: 1

In this example, TAN is used to calculate the tangent of ( \frac{\pi}{4} ) radians (approximately 0.785398163), which is 1. This demonstrates the TAN function's utility in performing trigonometric calculations within BASIC programs.

TIME (TI)

TYPE: Numeric Function

FORMAT: TI

Action: TI retrieves the current value of the interval timer or "jiffy clock," which ticks at 1/60th of a second intervals. This timer starts at zero upon system power-up and provides a method for tracking elapsed time in programs, though it is paused during tape I/O operations. By leveraging the TI function, programmers can implement timing features, measure durations, and synchronize processes within their BASIC programs.

EXAMPLE of TI Function:

10 PRINT TI/60 "SECONDS SINCE POWER UP"

This example demonstrates using TI to calculate and display the number of seconds elapsed since the Commodore 64 was turned on, showcasing TI's application in measuring time intervals and enhancing program functionality with time-based operations.

TIME$ (TI$) (string)

TYPE: String Function

FORMAT: TI$

Action: TI$ provides the current time as a string in the format of hours, minutes, and seconds based on the system's "jiffy clock." This timer offers a convenient way to track elapsed time or synchronize events within a program. Unlike TI, which returns the elapsed jiffies since power-up, TI$ presents time in a human-readable format. Additionally, TI$ can be set to a specific time, acting similarly to setting a wristwatch, which allows for custom time tracking starting from an arbitrary point. Note that TI$'s accuracy is compromised following tape I/O operations due to the pausing of the jiffy clock.

EXAMPLE of TI$ Function:

1 TI$ = "000000": FOR J = 1 TO 10000: NEXT: PRINT TI$

Output: 000011

In this example, TI$ is initially set to "000000" (midnight) and then a loop is executed to simulate a passage of time. After the loop, TI$ is printed, showing the elapsed time as "000011" (11 seconds), demonstrating how TI$ can be utilized for timing and delay functions in BASIC programming.

USR

TYPE: Floating-Point Function

FORMAT: USR(<numeric>)

Action: USR provides a mechanism for BASIC programs to call user-defined machine language subroutines. The address of the machine language subroutine must first be set in memory locations 785-786 using POKE commands. Once established, calling USR with a numeric argument transfers control to the machine language code. The <numeric> argument's value is passed to the subroutine by storing it in the floating-point accumulator (starting at memory location 97), where it can be accessed by the machine code. The result of the USR function is determined by the value left in the floating-point accumulator upon return to BASIC, enabling the integration of complex, high-performance routines within BASIC programs.

EXAMPLES of USR Function:

10 B = T * SIN(Y)
20 C = USR(B / 2)
30 D = USR(B / 3)

In this example, the USR function is used to call a machine language subroutine, passing it a fraction of B as an argument. This showcases how BASIC programs can leverage machine language code for tasks requiring higher computational speed or access to lower-level system functionality.

VAL

TYPE: Numeric Function

FORMAT: VAL(<string>)

Action: VAL converts a string to its numeric representation, allowing for the extraction of numbers embedded within text. The conversion process starts at the first character of the string and stops upon encountering any character that cannot be part of a numeric value, such as letters or symbols (with the exception of the decimal point '.' and the exponential 'e' for floating-point notation). If the string does not begin with a digit, a plus, or minus sign, VAL returns zero. This function is particularly useful in parsing numeric data from mixed-format strings or when numerical values are input or stored as strings.

EXAMPLE of VAL Function:

10 INPUT#1, NAM$, ZIP$
20 IF VAL(ZIP$) < 19400 OR VAL(ZIP$) > 96699 THEN PRINT NAM$ TAB(25) "GREATER PHILADELPHIA"

In this example, VAL is used to convert string ZIP$ to a numeric value to determine if it falls within a specific range. If the ZIP code is outside the given range, it prints the name with a label indicating "GREATER PHILADELPHIA," demonstrating VAL's utility in data validation and conditional logic within BASIC programs.

VERIFY

TYPE: Command

FORMAT: VERIFY ["<file-name>"] [, <device>]

Action: VERIFY is utilized to cross-check the contents of a program file stored on tape or disk against the version currently loaded in memory. This command is particularly valuable for confirming the integrity of a program following a SAVE operation, ensuring that the stored data matches the original without corruption or errors. VERIFY operates both in direct mode, for immediate execution, and within program sequences, providing a level of assurance that data storage processes have been completed successfully.

EXAMPLES of VERIFY Command:

  • VERIFY - Initiates a verification process for the first program found on tape. The system prompts the user to press play on the tape, then proceeds to search, find, and verify the program, ensuring its correctness.

  • 9000 SAVE "ME", 8:
    9010 VERIFY "ME", 8 - This example demonstrates saving a program to disk (device 8) and then immediately verifying it to ensure it was saved correctly. It highlights the use of VERIFY in conjunction with SAVE to validate the integrity of disk-based storage operations.

These examples illustrate how VERIFY can be employed to assure the accuracy and reliability of program storage on external devices, reinforcing data security practices in BASIC programming.

WAIT

TYPE: Statement

FORMAT: WAIT <location>, <mask-1> [, <mask-2>]

Action: WAIT temporarily halts the execution of a program until the specified condition at a given memory location is met, based on the provided mask(s). This command is primarily used for synchronizing the program with external events or specific hardware states by monitoring changes in I/O register bits. The memory location to monitor and the bit patterns defined by the masks are converted to integers. The program resumes once the condition defined by <mask-1> (and optionally <mask-2>) is satisfied at <location>. <mask-1> specifies the bits that must match exactly, while <mask-2>, if provided, specifies which bits should be ignored. It's a specialized command that's typically used in advanced programming scenarios involving direct hardware interaction or waiting for specific device responses.

EXAMPLES of WAIT Statement:

  • WAIT 1, 32, 32 - Pauses execution until the specific condition related to the device or memory location represented by 1 meets the criteria set by the mask 32.

  • WAIT 53273, 6, 6 - Halts the program until the memory address 53273 has the bits corresponding to the binary value 6 in the required state.

  • WAIT 36868, 144, 16 - Suspends program operation until the 128-bit (part of the 144 mask, binary 10010000) turns on or the 16-bit (binary 10000) turns off at memory location 36868.

These examples demonstrate the WAIT statement's utility in pausing program flow until certain conditions are met, typically related to hardware signals or status flags, showcasing its role in event-driven or hardware-integrated BASIC programming.

Basic Code Snippets

Hello World!

PRINT "HELLO WORLD!"
10 INPUT "WHAT IS YOUR NAME";N$
20 PRINT "YOUR NAME IS " n$
10 FOR I = 1 TO 100
20 PRINT I
30 NEXT I

Maze 1 liner

This is the famous Basic 1 liner maze.

10 PRINT CHR$ (205.5 + RND (1)); : GOTO 10

More info

Fibonacci Numbers

10 REM FIBONACCI NUMNBERS
20 A=1: B=1
30 PRINT A; B;
40 FOR I=3 TO 15
50 T=A+B: A=B: B=T
60 PRINT T;
70 NEXT

Find Primes

10 PRINT CHR$(147)
20 FOR N=1 TO 100
30 L = INT(SQR(N)):F=0
40 IF N<=2 THEN F=0: GOTO 80
50 FOR I=2 TO L
60 IF N/I=INT(N/I) THEN F=0: GOTO 100
70 NEXT I
80 IF N>=2 THEN F=7
100 POKE 1023+N,160
110 POKE 55295+N,F
120 NEXT N
140 GOTO 140

Guess the Number

10 PRINT "GUESS THE NUMBER BETWEEN 1 AND 100"
20 N = INT(RND(1) * 100) + 1
30 INPUT "YOUR GUESS: "; G
40 IF G < N THEN PRINT "TOO LOW! TRY AGAIN": GOTO 30
50 IF G > N THEN PRINT "TOO HIGH! TRY AGAIN": GOTO 30
60 PRINT "CONGRATULATIONS! YOU GUESSED IT RIGHT!"

Draw a Dot

10 FOR X = 0 TO 39
20 POKE 1024 + X, 160: REM DRAW DOT
30 FOR DELAY = 1 TO 500: NEXT: REM DELAY
40 POKE 1024 + X, 32: REM ERASE DOT
50 NEXT X