# Introduction
## Purpose

The purpose of this book is to teach both basic and advanced aspects of the TI-BASIC programming language. The book is designed to instruct newcomers with no previous TI-BASIC programming experience. Those who have some experience in programming can use the table of contents and appendices to inform themselves on certain aspects of the language, like optimizing code or learning the small, yet important differences between certain loop types.
Hopefully, the Wikibooks community can contribute a vast amount of useful TI-BASIC programming knowledge, which will allow this book to provide a much more in-depth look at TI-BASIC. Currently, it only provides information regarding TI-BASIC programming on the TI-83+ or 84+. Of course, the Silver Editions of the two calculators can be used with this guide (the only difference between the TI calculators and their Silver Editions is an increase in available memory).
To learn the language and programming skills from beginning to end, start with this page, the Introduction, and use the links at the bottom of each page to move on to the next chapter.

## Overview

TI-BASIC is a simple programming language used on Texas Instruments (TI) graphing calculators that integrates many normal graphing calculator commands, like calculations and graphing.
TI-BASIC is a relatively easy language to learn, especially when it is compared with Assembly, the other main language used to program TI graphing calculators. Programs written in TI-BASIC, compared to programs written in Assembly, have a small file size (due to the fact that commands like If and Menu use just 1 or 2 bytes of memory). However, this makes execution of TI-BASIC programs very slow, because the calculator first reads through and parses each line of code before translating it into assembly and executing it, similar to Python. In other words, it suffers from the same performance issues as any interpreted language. Despite its sluggishness, TI-BASIC is appropriate for making many simple programs.

## Conventions

A number of conventions are used in this book. Learning these conventions will aid in the learning process.
As this is a book designed to teach one how to program TI-BASIC programs, there will be several pieces of code throughout the chapter. Thus, special boxes have been designed so that one can easily find where certain portions of code exist.
There are three main code boxes: Syntax, Examples, and Output.

### Syntax

The commands in TI-BASIC must be typed in a particular format. The way a command must be stated is called the syntax. For example, Output (PRGM I/O 6) has certain restrictions. You must state the row, then the column, then the content in that order to display an output. This book explains syntax using boxes like this one:
* Where row is a number or real variable that will determine the vertical position of Content
** row can be a number between 1 and 8 (there are 8 lines of text on the screen)
* Where col is a number or real variable that will determine the horizontal position of Content.
** col can be a number between 1 and 16 (there are 16 characters across the screen)
* Where value is a string, number, equation, or variable of any type, that is to be displayed at the specified location.
No surprises here. TI-BASIC uses the same notation for functions as do many programming languages.

### Examples

Examples are just that. They are examples of commands in use, sometimes only containing one command, sometimes containing more. Often, there is more than one example for a given function, with different variations in the way the command can be used. Examples are formatted as follows:
Text to the right of a // represents a comment, used for explaining what the code is actually doing, line by line. This is only for display uses here in this Wikibook, and cannot be used in an actual program.
Usually, but not always, there will be an explanation either before or after the example.

### Output

The output is merely used to show how certain programs or functions would look on the calculator. If there is an example prior to the Output box, it is implied that the program was executed from the home screen. Outputs are displayed as follows:
The normal modes of entry can only use uppercase letters.

## Calculator vs. Computer
### Code

A calculator's screen has the width and pixels to show 16 characters in a row. This constraint is ignored in examples. While the code would be like this on the calculator:
    Disp "Hello, Wo
rld!","My name i s Bob"
It is still written this way in examples:
    Disp "Hello, World!","My name is Bob"

### Commands

In order to enter a command, like Disp, don't individually enter in the letters D i s p, but instead select the command from the program menu by pressing the PRGM key.
The Disp instruction can be found by pressing PRGM (while in the program editor) and using the right arrow key ⯈ to scroll over to the I/O menu. Then, press either 3 to immediately paste the command to the editor or use the down arrow key ⯆ to select the Disp command, then press ENTER.
To be concise, we write PRGM I/O 3 for the above. The instructions for accessing the command are included. If a command uses a menu name, it is stylized in italics. If 2ND must be pressed to open a menu, the menu will be bracketed in lieu of the actual key being pressed (e.g., 2ND MATH becomes 2ND [TEST]).
As an example, to access Pxl-Off(, we write 2ND [DRAW] POINTS 5. Press 2ND, PRGM (this will open the DRAW screen since 2ND was pressed), then navigate to POINTS, then press 5 or find the function Pxl-Off(, in the list.
Most instructions can be accessed through the Catalog 2ND [CATALOG], although this method is usually slower. To navigate the catalog quickly, you can jump to a specific starting letter by pushing the key with the related alpha letter.
Next: Necessary Items Table of Contents: TI-Basic Z80 Programming

# Necessary Items

To write TI-Basic Z80, you will need a compatible calculator. The list of calculators that use TI-Basic Z80 are:
* TI-83
* TI-83+
* TI-83+ SE
* TI-84+
* TI-84+ SE
* TI-84+ CE

## Other Utilities

It is also possible to use a virtual calculator, or emulator, to program and test TI-BASIC programs without a calculator. Virtual TI was one of the first emulators for TI calculators. Wabbitemu is currently the best free Z80 emulator, for both Windows and Mac users. To use an emulator, a ROM image is needed. It is a "snapshot" of the current state of a calculator. Wabbitemu can generate its own image, however, a ROM image can be obtained from any calculator using one of these methods. Texas Instruments has created its own excellent and all-inclusive emulator/debugger for the TI-83 and TI-83 Plus calculators, called TI-83 Plus SDK, as it is free for anyone who registers their owned TI calculator, and is found here, along with other Texas Instruments software.
The main advantage of using an emulator is that, while it may be convenient to write a program and test it on the fly on an actual calculator, it is faster to type-up code on a computer to test with an emulator. An added advantage is the ability to include lower case letters on TI-83 Plus calculators, though not on regular TI-83 calculators.
A common application for programming TI-BASIC on the computer is TI Edit. It allows the user to program as they would on a calculator, with built-in menus and functions. The drawback, however, is that TI Edit cannot run code. It can, however, save the code as a file that can be transferred to a calculator. The better thing to do is to use an emulator to test the programs you write before you transfer them onto a calculator. Remember to always back up your calculator before the transfer, because there is a small chance that the program will crash the operating system.
Normally, when buying a TI calculator, a CD is included with the set that includes computer software for coding on a computer and sending files to and from computers via a TI PC Link cable (not included). The link software provided by Texas Instrument is called TI-Connect, while the included program writing software is called TI-Graph Link, which can also be used as a linking program, but is out of date.
Other free 3rd party software can be found at ticalc.org, which has a large community of TI calculator owners and programmers. This specific page in ticalc.org's directory contains a large list of Windows, MAC, and UNIX related software.
Previous: Introduction Next: Hello, World! Table of Contents: TI-Basic Z80 Programming

# Hello, World!
## Opening and Navigating the Program Editor

To begin coding TI-BASIC on your calculator, you must use the program editor. This allows you to edit, manage, and run your programs. To access it, press PRGM NEW ENTER. Then, type in a short name for your program. The names for programs must follow these rules:
* Must include only uppercase letters and numbers, where the first character must be a letter
* Cannot include any other tokens, such as symbols or math functions
* Maximum length of 8 tokens long
Press ENTER, and an empty program will appear. In the following example, the program has been named EXAMPLE:
PROGRAM:EXAMPLE
To navigate the program editor, use the arrow keys to move the cursor, which is represented by a blinking black box. Press ENTER to move the cursor down a line, or to create a new line if the cursor is at the bottom-most line. To insert a line at any point, move the cursor to the end of the line above where the new line should be inserted. Then press 2ND [INS] ENTER. To clear a line, press CLEAR. Press DEL on any empty line to delete it.
Always, the first line (PROGRAM:EXAMPLE) on the screen shows the name of the program. It is not a line in the code, but rather a header to show the name of the current program. Press ENTER. Now, a new line on the program editor is created:
PROGRAM:EXAMPLE
In TI-Basic, colons (:) are used to signify new lines.
* Colons are automatically placed by the calculator when creating a new line. These colons cannot be deleted, except by deleting the line itself.
* Manually adding a colon (ALPHA [:]) also signifies a new line. These colons can be deleted.
To run a program, you need to first exit the program editor. Press 2ND [QUIT] to return to the home screen. Press PRGM and use the up and down arrows to select your program. Now, press ENTER twice: once to paste it to the home screen and second to execute it.
To stop a program during execution, press the ON key and an error will be thrown, stopping the program.

## Hello, world!

Now that you have learned how to navigate and perform simple edits on a program, now we will program our first program: the "hello world." This simple program tells the calculator to display the text HELLO, WORLD! on the screen.
PROGRAM:HLLOWRLD
    ClrHome
    Disp "HELLO, WORLD!"
Now, let's break down each line of this program and understand how it works.
    ClrHome
Every new line in a TI-BASIC program automatically starts with a colon. It's how the calculator knows when a line ends and a new line begins. ClrHome (PRGM I/O 8) is the instruction that clears the home screen, erasing any text or numbers that may have been on it.
    Disp "HELLO, WORLD!"
Disp (PRGM I/O 3) displays a variable, value, or string to the screen. If the screen is full, it will scroll down a line. If the string is more than 16 characters, Disp will only show the first 15 of them, followed by an ellipse (…). During the execution of the program, you will not be able to scroll and see the rest of the line if the 16 character limit is exceeded. Strings are displayed left-aligned, and values are displayed right-aligned.
In order to add quotation marks ("), press ALPHA +.
In this example, the string HELLO, WORLD! is printed to the screen.

## Alternate Method

Another command offered for printing to the screen is the Output (PRGM I/O 6) command. This command offers more arguments to specify where on the screen to print.
* Where row is the vertical positioning of the output. A value of 1 prints on the first row, etc.
* Where column is the horizontal positioning of the output. A value of 1 prints on the first column, etc.
* Where "text" or value is the text or value to be displayed to the screen.
Here's how to use this command in the "hello world" program. It prints HELLO, WORLD! at row 1 column 1:
    ClrHome
    Output(1,1,"HELLO, WORLD!")
This program will result in the same output.

## You try it!

Try these examples to practice the Disp and Output commands.

### Poem

Use the Disp commands to print a simple poem to the screen. Your poem should be 7 or fewer lines to fit on the screen (if you try to print an 8th line, the first line will move off the screen).

### Centered Text

Using Output, replicate the following output exactly. You will need to use the command more than once.
Previous: Necessary Items Next: Basic Variables Table of Contents: TI-Basic Z80 Programming

# Basic Variables
## What are Variables?

Variables are the meat of any programming language as they are used to store and work with data. With variables, the outcomes of programs can differ depending on the user's input or the purpose of the program. Variables in the TI calculators can store different types of data, whether it be numbers, lists of numbers, strings, mathematical functions, etc. However, each data type has its own type of variable that it can be stored in and the rules must be followed fairly strictly.
TI-BASIC is unusual among programming languages in that it does not support actual variables. Instead, all data are treated like files; there is no distinction between an ordinary number and an image, for example. TI refers to all files as "variables." Henceforth, "variable" will refer to a file usable by a program.

## Types of Basic Variables

There are many types of variables, but in this chapter, only the most common ones will be dealt with. The Advanced Variables section will deal with the more complex variable types and uses. The following sections will deal with:
* Number — numbers (e.g., 1, -0.5, 3.14, i, 3i+2)
* List — array of numbers (e.g., {1 2 3 4 5})
* String — text (e.g., "HELLO, WORLD")

## Storing and Recalling Variables

Variables can be stored and recalled at the home screen, or within a program by simply using that variable's name. The method for recalling variables varies depending on the type of variable:
* To type a number variable, press ALPHA, then the corresponding key for that letter.
* To type a list variable, press 2ND [LIST], then select the desired list in the list.
* To type a string variable, press VARS 7, then select the desired string in the list.
To recall the value of X, press ALPHA [X], then push ENTER:
or to recall Str1:
or to recall L1:

### Numbers

Numbers are stored into variables labelled A through Z and θ and can be real or complex numbers (complex numbers can only be used if the calculator is in a+bi or re^θi modes).
Number variables store both the integer and decimal part of a number. Examples of number variables are 0, 2.1, 5, 7.212, 3i, or 3.1415926. Number variables are accurate up to eight significant digits and can be in the range of -9ᴇ99 to 9ᴇ99 ($\pm 9*10^{99}$). If an attempt is tried to evaluate or store a value outside of the range, the calculator returns an error.
The calculator can update X, Y, R, θ, and T during graphing, so you may want to avoid using these variables to store non-graphing data.

#### Syntax

To store a number to a number variable, the syntax is as follows:
* Where value is a literal value, a variable, or an expression
* Where variable is the variable to store value to

#### Examples
##### Literals

5.32→X

##### Variable

A→X
In this example, only the value of A is stored to X (i.e., changes to A will not be reflected in X after the assignment).

##### Equation

10/2+36+89/A→X
In this example, if A = 89, X = 42, not the actual equation. Only the result of an equation is stored (the equation is 5+36+89/89 = 42, so X = 42).

### Lists

Lists are essentially an array: they store an array of numbers. The individual numbers of a list are named elements. The maximum number of elements in a list is 999.

#### Syntax

* Where value1,value2 through valueN are number elements
* Where listName is the name of a list. This can be one of two types:
** Calculator defined: L1, L2, L3, L4, L5, L6
** User defined: $_L$ (2ND [LIST] OPS B) followed by characters denoting a name, maximum of 6 tokens, letters only
* The amount of elements in a list may not exceed 999.
To instantiate a list, the following code is used:
    DelVar L1
    n→dim(L1)
It is important to first instantiate a list before attempting to access it so that the size is appropriate for usage. The dim( (2ND [LIST] OPS 3) command stands for dimension, and in this case, we have set n as the dimension (or size) of the list.
To access a single element in a list, use the format L1(N), where N is the N-th element in the list. The index is 1-indexed, so to reference the first element in L1, use L1(1).
Lists can only store numbers.

#### Examples
##### Literals

{15,20,30}→L1

##### Custom Named list

{1,2,3,4,5}→$_L$MYLIST

##### List to List

L1→L2

##### Equations

{15,20,30}+5→L1
In this example, L1 would consist of {20 25 35} because each element was increased by 5 then stored to L1.

### Strings

Strings hold text.

#### Syntax

* Where string is the string literal, or some other form of string to store to strN and
* Where strN is one of the predefined strings for the calculator.

#### Examples
##### Literals

"BOB SMITH"→Str1

##### Str to Str

Str1→Str2

##### Concatenation/Combination

"MY NAME IS "+Str1+" AND YOU KNOW IT!"→Str2

## Incompatible Types

It should be noted that variables can only contain their respective data type. For example, trying to store a number to a string object (0→Str1) will result in an error.

## You try it!

Try these examples to practice using the different data types.

### Arithmetic

Use variables to store numbers, then perform simple operations on them. Make variables A and B equal to 3 and 7, respectively. Then output $A/B$, $(AB)^{A}$, and $B+(A^{2+4B})$.

### List Operation

Create a simple list using these numbers: 3,6,8. Now, using Disp, output each value to the screen, then output the average of the values of the list by accessing them from the list. Remember, to type a list, press 2ND then a number from 1-6.

### String Concatenation

Set Str1 to your first name and set Str2 to your last name. Then, using string concatenation, print your first and last names on two lines, with preceding text FIRST: and LAST:. For example, your output would appear as follows:
Previous: Hello, World! Next: Output Table of Contents: TI-Basic Z80 Programming

# Output

There are a few different ways to display text and values to the screen in TI-Basic. These include Disp, Output, Pause and Text. We'll cover each of their uses and their syntaxes.

## Disp

Disp (PRGM I/O 3) displays text or values to the home screen. It creates a new line on the home screen and prints the text left-aligned for strings, and right-aligned for values.
* Where valueA, etc., are strings or values
To print Str1 to the home screen:
    Disp Str1
To print X to the home screen:
    Disp X
To print a literal string or value to the home screen:
    Disp "HEY!"
    Disp 3/2
There can be multiple expressions or variables with each having its own line:
    Disp "HELLO","WORLD"
An example of a simple program that uses Disp:
    ClrHome
    3.14→X
    Disp "THE VALUE OF
    Disp "X IS"
    Disp X
If you try to print a string or value that is longer than 16 tokens, it will be trimmed and appended with an ellipse:
    ClrHome
    3.14→X
    Disp "THE VALUE OF X IS"
    Disp X
If no arguments are added, the home screen is displayed.

## Pause

Pause (PRGM CTL 8) freezes the program mid-execution and can optionally display text as well. When a pause token is reached in the program, execution pauses until the user presses ENTER to resume. If text is passed as an argument, the specified text will be displayed.
* Where value is a string or value
* Where time is a time defined in seconds. Time is rounded up to the next tenth.
Some examples of Pause:
    Pause "Please press ENTER to continue"
    Pause "Resuming in 3 seconds.",3
Text displayed with Pause can longer than 16 tokens. However, you will need to use the left and right arrow keys to scroll along the text. If no text is provided, the program will simply pause until ENTER is pressed:
    Pause

## Text

Text (2ND [DRAW] DRAW 0) draws small font text to the graph screen. It has precise X and Y coordinate positioning, and can print several values or strings.
* Where row is the pixel row for the bottom of text to be printed on
* Where column is the pixel column for the left of the text to start printing at
* Where text1, etc., are strings or values
* Notice that this command inverts the x and y coordinates when displaying text and that it starts from the upper left 1,1 coordinate.
Some examples of using Text:
    Text(1,1,"Hi!")
    Text(20,20,A+B)
If the first argument passed is -1, Text will draw with the standard font:
    Text(-1,20,40,"Big text!")

## Output

Output (PRGM I/O 6) is used for displaying values or strings on the home screen. Output will override anything that the displayed characters may overlap with that is previously on the screen.
* Where row is the vertical positioning of the output. A value of 1 prints on the first row, etc.
* Where column is the horizontal positioning of the output. A value of 1 prints on the first column, etc.
* Where "text" or value is the text or value to be displayed to the screen.
    Output(2,6,"WIKIBOOKS")
In this example, the calculator would display WIKIBOOKS at 2 rows down (from the top of the screen) and 6 columns over (from the left of the screen). Notice that to display a string, the string must be enclosed in quotation marks. Make sure to separate values of row column and display value with commas.
* To display a numerical value, do NOT place quotes around the value, as it is not a string.
* Only one value can be displayed per Output statement.
Previous: Basic Variables Next: Input Table of Contents: TI-Basic Z80 Programming

# Input

Input functions accept data from the calculator's user. Input and output functions can be found under PRGM I/O.

## Input

Input (PRGM I/O 1) accepts both keyboard and graph point data.
* If no variable is passed, Input will open the graph and the user will select a point by using the arrow keys and ENTER.
* If a variable is passed, Input will store the user's input into this variable.
* If a string or text is provided with the variable, the text will be displayed and the user input will follow on the same line.
Input without a variable will open the current graph and pause the program. The arrow keys can be used to move the cursor. When ENTER is pressed, the variables X and Y will be updated with the X,Y position of the cursor. In PolarGC mode, R and θ will be updated instead.
If a variable follows Input, the program will accept a value from the keyboard and store it in the variable when ENTER is pressed.
If the format Input "string",variable is used, the calculator will display up to 16 user-defined characters before accepting input. If Strn is used, Strn is string number n, accessed with VARS 7 n. Note that "text" must be contained in quotation marks (ALPHA ["]).

### Examples

This code returns the X,Y coordinates of the graph cursor:
    Input
    Disp X,Y
This code accepts a value from the keyboard, stores it in the variable called A, and displays it:
    Input A
    Disp A
This code displays what the program is looking for, accepts and stores a numeric value from the keyboard in the variable called A. Then A is displayed:
    Input "APPLES",A
    Disp A

## Prompt

Prompt (PRGM I/O 2) gets user input for one or more variables at a time. It displays the variable name followed by =? for each variable, waiting for keypad input followed by ENTER before continuing. Each value entered is stored in its respective variable.
Prompt is useful for quick user input, but should be avoided due to the limitation that only the variable name can be displayed.

### Examples

Displays the following:
Displays the following (with user input):

## You try it!

Try these examples to practice getting and handling user input.

### Pythagorean Theorem

The Pythagorean Theorem states that, for any right triangle with legs A and B and hypotenuse C, $A^{2}+B^{2}=C^{2}$. Write a simple program that can calculate the hypotenuse C given values A and B, and display it to the screen. You can use the Input or Prompt commands.

### Greeting

Write a program that asks the user what their name is, and respond, using their name.
Previous: Output Next: Conditional Statements Table of Contents: TI-Basic Z80 Programming

### Age Calculator

Write a program the allows the user to enter their age in years, then display their age in hours, then in minutes, then in seconds.

# Conditional Statements

Conditional statements allow a program to take a different path depending on some condition(s). These allow a program to perform a test and then take action based on the result of that test.

## Conditions

Conditions are used to control the path of a program. Conditions perform comparisons between different values through the use of relational operators. These include =, ≠, >, ≥, <, ≤. Relational operators always return a true or false result (known as a boolean). To use them, type the values to compare against on either side of the operator:
To type relational operators, press 2ND [TEST]. You may also want to test two different conditions at the same time and join them using a logical operator. These include and, or, xor, and not. The basic syntax is similar to those of relational operators.
To type logical operators, press 2ND [TEST] LOGIC. For the following list, consider the format A op B, where A and B are conditions, and op is a logical operator. Where op equals...
* and, the entire condition returns true only if A and B are both true.
* or, the entire condition returns true if at least one of A and B is true.
* xor, the entire condition returns true only if one of A or B is true.
The not operator is special because it does not directly compare two conditions. Instead, it negates the condition(s) that are nested inside. For example:
To use conditional statements, they must be placed into a conditional block. Conditional blocks contain the condition to test and the code to execute. The following sections describe the various types of conditional blocks available in TI-Basic.

## If

If (PRGM CTL 1) requires a criteria argument (condition) to be stated which determines whether the following instruction is to be executed. A standard If block can only run one line of code dependent of the condition. For example, if you needed to execute two or more instructions dependent of the condition, you must use an If Then End block. The argument or arguments is a boolean result, meaning that they will be true or false. If an expression is used as the condition, 0 will represent false and non-0 values will represent true.

### Syntax

* Where condition is any statement resulting in a zero or non zero result, or a conditional operator returning true or false
** If condition returns true or non-zero, statement is executed
** If condition returns false or zero, statement is not executed

### Examples

The following example demonstrates a very basic If statement:
    6→X
    If X>5
    Disp "X > FIVE!"
It will display X > FIVE! because the condition X>5 returns true (6 is greater than 5). If X had been 3, condition would return false (3 is not greater than 5), and nothing would display.
The following program will always display Hello World because the condition 1 will always return 1 (which is non-zero) and therefore the condition is always true:
    If 1
    Disp "Hello World"
and likewise the following will never display Goodbye World because it always returns 0.
    If 0
    Disp "Goodbye World"

## If Then End

If Then End (PRGM CTL {1,2,7}) conditional statements are used when more than one statement must be executed if a condition returns true. It is very much like the simple If statement, with the difference that multiple statements are executed instead of one.

### Syntax

The If statement requires a condition, then a Then command must follow on the next line, followed by one or more statements which will execute if the condition returns true. The If block is ended by a End statement which tells the calculator that all following statements are to be executed as normal.
* Where condition is any statement resulting in a true or false result.
** If condition returns true, statement1, statement2... statementn (all statements between Then and End) will execute
** If condition returns false, the statements between Then and End are not executed, and the program continues with the first statement after End
It is also common to manually insert a colon directly after the condition of the If, then type Then. As an example:

### Example

    Prompt X
    If X≥5
    Then
    Disp "You entered",X
    Disp "X ≥ 5"
    End
When the program is run, it will be displayed as:

## If Then Else End

If Elses are used when the programmer needs to make a choice where if the condition returns non-zero, statements are executed, but if the condition returns zero, other statements are executed. Either way, only one set of instructions are executed.

### Syntax

* Where condition is any statement resulting in a zero or non zero result.
** If condition returns nonzero, trueStatements (instructions between Then and Else) will execute, then the instruction after End is executed
** If condition returns zero, falseStatements (instructions between Else and End) are executed, then the instruction after End is executed

### Examples

    If X≥5
    Then
    Disp "Hello World I'm"
    Disp "Big like five"
    Else
    Disp "Goodbye World"
    Disp "I'm small like four"
    End
Would display
If X were greater than or equal to five, but would display the following if X were less than five:

## Else If Workaround

It should be noted, TI-Basic does not support else if statements. However, to workaround this, nest the conditional blocks in the Else portion of the block. For example, in a traditional programming language, the following...
if (condition1) {
} else if (condition2) {
} else if (condition3) {
} else {
would be notated as, in TI-Basic:
    If condition1
    Then
    statements1
    Else
    If condition2
    Then
    statements2
    Else
    If condition3
    Then
    statements3
    Else
    statements4
    End
    End
    End
However, this is hard to read, so for this example, we will add spaces to make it more clear (You cannot add extra white space in practice. You will receive syntax errors.):
    If condition1
    Then
    Else
    End

## You try it!

Try these examples to practice using conditional statements.

### Even or Odd

Write a program that, when given a number, determines if the number is even or odd and prints the result to the screen.
To help you write this program, you can use remainder( (MATH NUM 0). It returns the remainder after diving a dividend by a divisor. The syntax for remainder( is:
Older versions of the TI-84 Plus and the TI-83s do not have a function for calculating the remainder. However, this is still calculatable via an alternate solution:
* Where A is the dividend and B is the divisor.

### BMI

Body mass index (BMI) is a value derived from the mass and height of a person. A person's BMI is calculated with the following formula: ${\frac {{\text{weight}}_{\text{kg}}}{{\text{height}}_{\text{m}}^{2}}}$. The value of a person's BMI can be categorized by the following table:
| BMI | Category |
| < 18.5 | Underweight |
| 18.5-24.9 | Healthy |
| 25-29.9 | Overweight |
| 30+ | Obese |
Write a program that accepts user input for the person's weight in kilograms and their height in meters, and display their BMI and their category.
Previous: Input Next: Loops Table of Contents: TI-Basic Z80 Programming

# Loops

It is important while writing programs to save space due to the calculator's limited memory. To help this, loops can be used which can repeat a section of code a number of times. TI-Basic offers a few types of loops: While, For, and Repeat.

## While

The While (PRGM CTL 5) loop executes a block of commands between the While and End commands as long as the specified condition is true. The condition is tested at the beginning of the loop (when the End command is encountered), so if the condition is initially false, the block of commands will never execute.

### Syntax

* Where condition is any statement resulting in a true/false/zero/non-zero result
** If condition returns true or non-zero, statement continues to execute
** If condition returns false or zero, statement will not execute and will skip to after the End

### Examples

The following example demonstrates a very basic While Loop that will display X until Y equals 0:
    While Y≠0
    Disp X
    End

## For

The For (PRGM CTL 4) loops executes a block of commands between the For and End commands n number of times. For is useful when you know the exact number of times you want to repeat a section of code.

### Syntax

* Where variable is a Real (A-Z & θ). This variable represents a counter.
* Where begin is the number to being counting from
* Where end is the number to stop exectution once variable equals end
* Where, optionally, increment is the amount to change variable after each loop. If this argument is not passed, it is assumed to be 1.

### Examples

To print the numbers 1 to 5 using a For loop:
    For(I,1,5)
    Disp I
    End
This code will print:
To traverse a list and print its elements:
    For(I,1,dim(L1))
    Disp L1(I)
    End

## Repeat

The Repeat (PRGM CTL 6) loop executes a block of commands between the Repeat and End commands until specified condition is true. The condition is tested at the beginning of the loop (when the End command is encountered), so if the condition is initially true, the block of commands will never execute.
Repeat is simply While where the condition is inverted.

### Syntax

* Where condition is any statement resulting in a true/false/zero/non-zero result
** If condition returns false or zero, statement continues to execute
** If condition returns true or non-zero, statement will not execute and will skip to after the End

### Examples

The following example demonstrates the use of a Repeat statement. It will continue to ask the user for an X value until X > 5 :
    0→X
    Repeat X>5
    Prompt X
    End

## You try it!

Try these examples to practice using loops.

### Summation from 1 to n

Write a program that asks the user for a number n (must be greater than 1) and prints the sum of the numbers 1 to n. For example, if n = 6, the program would display 21 ($1+2+3+4+5+6=21$).
Solution :
0→N // Clear n
Repeat N>1 // Until n is greater than 1,
Prompt N // Ask for n
End // End repeat loop
0→S // Clear s (sum)
For(X,1,N) // From 1 to n,
S+X→S // Add X to S
End // End for loop
Disp S // Print
Alternate solution using summation
0→N // Clear n
Repeat N>1 // Until n is greater than 1,
Prompt N // Ask for n
End // End repeat loop
Disp Σ(X,X,1,N) // Summation Σ(expression,variable,start,end)
This example uses the following summation expression: $\sum _{i=1}^{N}x_{i}$ :

### Fibonacci Sequence

The Fibonacci Sequence is defined as $F(n)=F(n-1)+F(n-2)$ where $F(1)=0$ and $F(2)=1$. Therefore, the first 10 elements of the sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. Write a program that stores the first 100 elements of the sequence to L1, then display them. Remember, you will have to instantiate the list first.

### FizzBuzz

FizzBuzz is a children's game often used today as a programming evaluation program. The original game consists of players taking turns to count incrementally, replacing any number divisible by 3 with the word "fizz", and any number divisible by 5 with the word "buzz". For this example, write a program that counts from 1 to 100, replacing numbers divisible by 3 with "Fizz", 5 with "Buzz", and 3 and 5 with "FizzBuzz."
Hint: Take the remainder of the current value and the key numbers and compare it to 0.
You will have to get creative writing this program as there are many ways to approach it. The following solution is just one of many solutions:
Solution :
In this example, we must check multiples of 15 before checking 3 or 5.
:ClrHome
:For(X,1,100)
:If remainder(X,15)=0:Then
:Disp "FIZZBUZZ"
:Else
:If remainder(X,3)=0:Then
:Disp "FIZZ"
:Else
:If remainder(X,5)=0:Then
:Disp "BUZZ"
:Else
:Disp X
:End
:End
:End
:End
Solution without remainder
:ClrHome
:For(X,1,100)
:If fPart(X/15)*15=0:Then
:Disp "FIZZBUZZ"
:Else
:If fPart(X/3)*3=0:Then
:Disp "FIZZ"
:Else
:If fPart(X/5)*5=0:Then
:Disp "BUZZ"
:Else
:Disp X
:End
:End
:End
:End :
Previous: Conditional Statements Next: Advanced Variables Table of Contents: TI-Basic Z80 Programming

# Advanced Variables

The calculator can work with variables of other types in programs. Here, we show some examples of manipulating and accessing all other types of variables from a program. It is assumed you understand basic operation of the variable types.

## Complex

Complex numbers on the calculator use the same variables as Real numbers. So, the A variable can hold both 3.14 and 3i+2, but not at the same time. Essentially, you do not have to use different types of variables for real and complex numbers.

## Matrices

Matrices store data in two dimensions, much like a table. To instantiate a matrix:
    DelVar [A]
    {x,y}→dim([A])
To get and set a value in the matrix:
    [A](x,y) // Get a value
    3.14→[A](x,y) // Storing a value

### Examples
#### 4x4 Multiplication Table

    DelVar [A]
    {4,4},dim([A])
    For(I,1,4)
    For(J,1,4)
    I*J→[A](I,J)
    End
    End
    Disp [A]

#### Hadamard Product

The Hadamard product for two matrices of equal dimension is (in this example 3x3 matrices):
${\begin{bmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\end{bmatrix}}\circ {\begin{bmatrix}b_{11}&b_{12}&b_{13}\\b_{21}&b_{22}&b_{23}\\b_{31}&b_{32}&b_{33}\end{bmatrix}}={\begin{bmatrix}a_{11}\,b_{11}&a_{12}\,b_{12}&a_{13}\,b_{13}\\a_{21}\,b_{21}&a_{22}\,b_{22}&a_{23}\,b_{23}\\a_{31}\,b_{31}&a_{32}\,b_{32}&a_{33}\,b_{33}\end{bmatrix}}$
This code performs the Hadamard product of Matrix A and B and stores it into Matrix C:
    DelVar [C]
    If sum(dim([A])≠dim([B]))≠0 // Comparing lists
    Stop
    dim([A])→L1
    L1→dim([C])
    For(X,1,L1(1))
    For(Y,1,L1(2))
    [A](X,Y)*[B](X,Y)→[C](X,Y)
    End
    End

## Y-Vars

The Y-Vars are special strings that hold the expressions used in graphing. They operate just like normal strings, but are used when graphing and are parsed as expressions. Entering a string into a Y-Var will allow it to be graphed on the screen. Use the letter X to denote the variable, just like you would when entering an equation into the Y= screen.

### Examples
#### Simple Graph

    ZStandard
    "3X+2"→Y1
    DispGraph

## Pics

Pics store a snapshot of the graph screen, including all the drawings made to the graph screen. Pics do not store the equations that make up the drawing, but rather just the pixels that are colored.
To store and recall Pics means to write and read pics, respectively:
Where n is a number from 0–9, or a Pic variable like Pic1.

## Graph Databases

Graph Databases (GBD) are used for storing the current graphing information. It includes:
* The current graphing mode (one of FUNC, PAR, POL, or SEQ)
* All graphing equations in the current mode
* Window variables excluding zoom and table settings
* Graph formatting
To store and recall GBDs:
Where n is a number from 0–9, or a GBD variable like GBD1.
Previous: Loops Next: GetKey Table of Contents: TI-Basic Z80 Programming

# GetKey

When writing certain TI-Basic programs, it can be useful to get individual key presses for advanced menu handling or games. This can be achieved via the getKey (PRGM I/O 7). getKey returns the numerical value of a key press at the instance of the instruction execution.

## Key Code Diagram

The value that is stored into variable is a special number that represents the key that was pressed. The diagram to the right shows the value that corresponds to the key.
Each key has a two or three digit number assigned to it. The first digit, or two digits if the number is three digits, is the key's row number (how far down on the calculator the key appears) and the last digit is the key's column number (how far across on the row the key appears). Thus the SIN key is in the 5th row and the 2nd column, so its code is 52. The only slight exception to this is the arrows keys. ←, ↑, and → are all considered part of the second row and are numbered as such. ON doesn't have an accessible numerical value (theoretically it should be 101; however, it acts as the program break button).

## Usage

Because getKey only returns the key press during the instruction of the command, it will often return 0 since no keys were pressed while command was being executed. However, the getKey command can be run on a loop, allowing for user input to be registered at any time.
To do so, use this simple code:
    0→K
    Repeat K
    getKey→K
    End
This program will wait until the user presses a key on the keypad, then will break out of the loop and continue execution. Since getKey returns 0 if no keys are pressed, the code repeats since Repeat will loop if the condition is 0 or false.
Note that the variable K is the de facto variable to store getKey to.
It is possible to shave off 4 bytes by using Ans:
    Repeat Ans
    getKey
    End
If getKey is called, but not stored to a variable, the value will be stored into Ans.

## You try it!

Try these examples to practice using getKey.

### Player Movement

Using getKey, draw a player (use a single character like *) on the screen and allow the user to push the arrow keys to move the player in X and Y directions. Make sure the player won't go off the screen.
Previous: Criteria Instructions Next: Menus Table of Contents: TI-Basic Z80 Programming

# Goto and Lbl

Goto (PRGM CTL 0) and Lbl (PRGM CTL 9) are used to jump to different sections in the program. However, these should be used sparingly, since having many Gotos can make the program very convoluted and difficult to understand.

## Syntax and Usage

Where label is a one or two character code that only includes 0–9, A–Z, and θ.
When the program executes a Goto statement, it jumps to the corresponding Lbl with the same label. If the specified Lbl does not exist, a label error is thrown.
For example, observe the following program:
    Goto A
    Lbl A
    Disp "HI!"
    Lbl B
    Disp "HELLO!"
You may think that this program will display HI!. However, the following is actually displayed:
This is because after the Disp command after the first Lbl, the program continues past the second Lbl and continues executing statements. To prevent the program from continuing to execute instructions, Stop (PRGM CTL G) can be used, which simply stops the current program.
    Goto A
    Lbl A
    Disp "HI!"
    Stop
    Lbl B
    Disp "HELLO!"
    Stop
This modified program simply displays:
Previous: GetKey Next: Menus Table of Contents: TI-Basic Z80 Programming

# Menus

Menu( (PRGM CTL D) is useful for allowing the user to select an option. By using Menu(, you can list several choices which the user can pick; each choice jumping to a different label.

## Syntax

The basic syntax for Menu(:
* In place of any text string, you may substitute a string variable name (e.g., Str1)
* title can have a max length of 16 characters
* Each choice can have a max length of 14 characters, any additional characters are truncated
* Menus can have a limit of 7 options. Attempting to add more options than 7 will result in an ARGUMENT error being displayed upon attempted command execution.
When a user selects an option in the menu by pressing ENTER, the program will jump to the Lbl with the same name defined in the Menu( statement.
If the Menu( statement references a Lbl that does not exist, a LABEL error will be returned.

### Example

To create a simple menu with several options:
    Menu("PHYSICS","PE",A,"KE",B,"WEIGHT",C)
    Lbl A
    statements
    Lbl B
    statements
    Lbl C
    statements
Displays the following when executed:

## Advanced Menus

The Menu( function allows for great use of static menus, but when more choices are needed or when more interactive, dynamic menus are needed. The following method uses getKey to achieve this.
Note: The following example uses the Text command, which draws text to the graph screen. This is covered with more detail in later chapters.
    statements
    Lbl B
    statements
    Lbl C
    statements

## You try it!

Try these examples to practice using the Menu( command.

### Physics Calculations

The potential energy of an object is defined by $PE=mgh$, where m is the mass in kilograms, g is the gravity, and h is the height in meters. The kinetic energy of an object is defined by $KE={\frac {1}{2}}mv^{2}$, where m is the mass in kilograms and v is the velocity in meters per second. The apparent weight of an object is defined by $W=mg$, where m is the mass in kilograms and g is the gravity. Use the Menu( command to write a simple program that the user can select from each of the previously defined formulas, enter known values, and receive an output.
Previous: GetKey Next: Errors Table of Contents: TI-Basic Z80 Programming

# Errors

When programming on the TI-84, the calculator will assume the written code is valid. If, as it executes the code, finds an unexpected token, or encounters an otherwise invalid statement, the TI-84 will throw an error. The calculator will stop executing the code in the program and display the type of error on the screen. There are two types of errors: syntax errors and runtime errors.
For example, consider the following example:
The syntax for the Output( command expects two integers, then a string. In this example, the second argument is a string, which the calculator does not know how to interpret. In this case, the calculator throws an error:
Code execution halts and a menu is displayed. The first option quits the program and returns to the home screen. The second option will open the code editor and scroll to the line in the code where the error occurred.
The second type of error is a runtime error. These errors can't necessarily be detected by the appearance of code. Consider the following example that displays the reciprocal of the entered value:
    Disp A$^{-1}$
The code works fine in most scenarios:
However, consider when the user inputs 0:
This behavior can be unwanted, since the code halts and does not continue executing if an error occurs. Therefore, it is important to consider all edge cases for calculations and statements. In this case, the line :If A≠0 before Disp would prevent an error.
Runtime errors do not necessary have to display an error to be an error. For example, a program that is expected to display the even letters of the alphabet, but instead displays the odd letters of the alphabet, would have a runtime error since the program does not function as expected. These can be the hardest and easiest errors to fix!

## You try it!

Examine the following examples, identify which kind of error is presented, and a fix to resolve the error(s).
The following program should store 10 random numbers in L1, but contains an error. Find, identify, and fix the error.
    0→dim(L1
    For(I,1,10
    rand→L1[I]
    End
In this example, the program should output the largest number in L1 (this program assumes there is at least one value in L1).
    -9E99→L
    For(A,1,dim(L1
    If L1(A)>L
    A→L
    End
    Disp L
Previous: Menus Next: Tips, Tricks and Optimizations Table of Contents: TI-Basic Z80 Programming

# Tips, Tricks and Optimizations

This chapter will focus on writing good practice code, including various tips, tricks, and optimizations you can apply.

## Editing on the computer

Editing programs on the calculator can be extremely cumbersome; scrolling is slow, and program structure is hard to visualize. Also, calculators can lose power or freeze, which will destroy the current program and all other programs not archived. TI provides freely-downloadable "Graph Link" software, which is difficult to use, but is easier than manually programming on the calculator. It allows you to display messages in lowercase and write-protect programs. Unfortunately, the Windows version is not integrated into the TI Connect software, which is necessary to transfer your programs to the calculator.
** Graph Link allows you to type strings with lowercase letters, which results in a better user interface.
** You can "lock" a program, which prevents display of the code on the calculator, so you (or your friend) cannot accidentally mess up the program.
** Fortunately, the Mac OS X version of TI Connect is much more powerful than its Windows counterpart, and allows for editing programs.

## Program Optimization

As in optimization with other program languages, most TI-BASIC programs can be optimized in two ways: size optimization (makes the program take up less room on the calculator) and speed optimization (makes the program run faster). Often, improving the size of the program helps increase its speed and vice versa. Some basic tips that apply on BASIC programs follow:

### Learn more commands

TI graphing calculators have many commands built in. To access them go to the catalog. On the 83+/84+ the catalog can be displayed by pressing 2ND [CATALOG]. Some commands allow you to drastically shorten and speed up your TI-BASIC programs. For example, the abs( function automatically chops of the negative sign of a number. abs(-2) will return 2. This is faster and more compact than writing out if/then statements that chop off negative signs.

### Use Lbl/Goto loops only when needed

Whenever you can, replace them with While, For( and other loops. This makes your code smaller, faster and a lot easier to read. Sometimes you absolutely need labels; do not be afraid to use them, but replace them whenever practical.

### Use text with the Input function

You can place a single line of text after the input function using quotation marks. Follow this by a comma, then a variable. This saves you from having to use the Disp function and saves space (e.g., :INPUT "What number?",A instead of :Disp "What number?" :Input A).

### Leave off ending quotes and parentheses

At the end of every line in a TI-BASIC program, the calculator does not care if you leave off your ending quote or your parenthesis. So, instead of typing :A+abs((2X+3)Y) you should type :A+abs(Y(2X+3 to save space. However, you should do this only when releasing a program (keep the original!) since it is more difficult to understand and edit. Not all commands or functions may allow this.

### Simplify equations

This can be a more difficult task to one who is unfamiliar with equation manipulation learned from many algebra classes. A smaller, more simplified equation usually can run faster and be smaller in size. It is an important note that parentheses also count as a single byte.
(x + y) / z can be z$^{-1}$(x + y. This is because there is a $^{-1}$ function right on the calculator that takes up a single byte, so in theory, you are saving a single byte by taking away a parenthesis. The * command is not necessary, since it can replaced with nothing: A*B becomes AB and A/(B*(C+4*F)) becomes A/(B(C+4F.
It may not sound like a lot, but it adds up quickly!

### Find the function

Whenever possible, use a built in function instead of using a loop. For example, instead of writing:
    0→A
    For(X,1,len(L1
    A+L1→A
    End
Write:
    sum(L1)→A

### Use constants that are available to you

Instead of typing out 3.14 or 2.72, use π and e, respectively. The variables have much more precision and allow you to save space by using the token instead of the value.

### Use as few variables as you can

Variables take up 18 bytes. If you use all 27 variables (not including available string and list spaces), this uses 486 bytes. This is sometimes more than the program itself. Simplify formulas as best you can. You can always use the Ans variable. Simply state the formula in your code without saving it into a variable. This puts the answer/result into the Ans variable itself. The Ans variable does not take up extra space because it always exists and always changes.

### Use Subroutines

Often, in larger programs (on the scale of 5+ KB) there are repeating portions of the program (or very close bits). Make small programs that perform complex, repeated tasks. For example, suppose you have a program that performs a complex calculation multiple times. Instead of rewriting the complex calculation multiple times, write it once as a different program. Then, you can mention the program name in one line multiple times instead of writing out something long and complicated multiple times. The way to do this is to treat the separate program as a "black box." The "black box" must manipulate values from the Ans variable. For example, consider these paired sets of code, which square a number twice and add one to it (prgmSQUARE does the repeated task of squaring the number):
    Prompt A
    A
    prgmSQUARE
    Ans
    prgmSQUARE
    Disp Ans+1
prgmSQUARE:
    Ans^2

### Watch out for stack overflows

Any use of If Then Else, While, or other statements that are ended by End causes the program to use some more memory, because it has to remember that that statement has to be closed by an End. Avoid using Goto to escape these blocks, or end them at your destination, otherwise if you do this often, you can get a memory error and you slow down your program fast.

### Make good use of the 'Ans' variable

Ans can store just about anything. If you have a big statement containing a number that you frequently reference, for example 100, it is possible to use Ans to save space. For example:
    Pxl-On(100,10
    Pxl-On(100,20
    Pxl-On(100,30
    Pxl-On(100,40
can be reduced to:
    100
    Pxl-On(Ans,10
    Pxl-On(Ans,20
    Pxl-On(Ans,30
    Pxl-On(Ans,40
which could be further reduced to (it is actually more efficient to use 100 since it is only needed once):
    For(I,10,40,10
    Pxl-On(100,I
    End
Having a single value on one line of code is, surprisingly to those who write in other languages, a valid statement. It stores the value into Ans.

### Don't run code you don't use

This is one optimization that can speed up your games tremendously. Instead of letting the program run through an entire For( / While / Repeat loop, you can end it prematurely with an If:
    For(A,1,len(L1
    If L1(A)=4
    End
    End
The above example will break the For( loop if the value is 4.

### Calculate positions at display

Instead of displaying text or a glyph for a program after its X,Y coordinates have been calculated, put the formulas where you would normally put the X,Y variables. For example, instead of going through a bunch of If statements to find the string length of a number, you can use the log( operator inside your Output( or Text( commands to dynamically find its string length and display it at the correct position.

### Only clear what you need to

To save time for drawing graphics for games, don't use clear draw or clear home commands. The calculator takes a long time to clear the entire screen. Instead, you can output blank spaces to clear. For example, you have a symbol representing a spaceship. Instead of redrawing the whole screen when the spaceship's position changes, just draw blank spaces where its old position was and draw the new spaceship on top.

### Pause calculations using For(

An easy workaround to pause the current state of your program for a small amount of time would be to use a blank For( loop. For example, to pause the game when a message pops up:
    For(Ans,1,30
    End
Use this wisely, however, since it will pause all user input as well. (unless you put some code in the for loop)
Nearly always optimization requires creativity to be implemented properly and successfully.

## Tips

If you must program on your calculator, there are several ways to make editing easier.
* Use CtlgHelp. Download and install the CtlgHelp app on your calculator. It requires 32 KB free space. This app is a useful syntax reference. To access help, highlight a command in a menu or the Catalog and press the + key.
* Use a Plus Silver Edition calculator. If you can afford it, buy a "Plus Silver Edition" calculator, which is faster and has more memory.
* Backup your programs. When you finish writing or using a program, immediately archive it (this saves the program from RAM to an internal flash disk). Programs which are archived will survive a power loss and most crashes, but those in RAM will disappear. This is only recommended if you only have to protect a single program. Use groups to backup multiple programs. You may find CalcUtil useful because it will allow you to edit and run archived programs, thus protecting everything from accidental deletion.
** If your program saves permanent data, such as a notepad or to-do list, archive the file after reading or writing. The data file will thus be protected against power loss or crashes. However, this will significantly degrade performance, so it should not be used for large quantities of replaceable data that must be accessed quickly (such as a list of random numbers).
** Alternatively, you can back up multiple programs in one group, which can be created in the memory menu. Groups must contain at least two objects (programs or variables).

## Tricks

* Copy-and-paste code. Let's say you have a program with code you don't want to rewrite in your main program. First navigate to the place in your main program where you want to insert code. Then, press 2ND [INS] 2ND [RCL] PRGM PRGM. Navigate to the name of the program containing the code you want to copy. Then, press ENTER.
* Draw fast circles. Insert {i} as the last argument in your circle command. For example, this quickly draws a circle of radius 5 centered at (0,0): :Circle(0,0,5,{i}).
Previous: Errors Next: Advanced Programming Table of Contents: TI-Basic Z80 Programming

# Advanced Programming

This section will focus on advanced programming techniques which will help you manage your code better and create advanced coding structures.

## Idioms

Idioms are pieces of code that are used repeatedly from program to program.

### Invisible "Done"

the following code will clear the screen and get rid of the Done that follows programs. If the last command that alters the screen (e.g., Disp, ClrHome, etc.) is Output(, then Done will not appear.
    ClrHome
    Output(1,1,"
A different solution is to set a variable, string or a number at the last line. That value will be shown at the end of the program. So to remove Done, just put an empty string at the end of your program.
    ClrHome

### Booleans

Note that boolean values are represented by 1 and 0 where 1 is true and 0 is false. This makes integrating true/false conditionals into equations very convenient.
Never use = tests for boolean values. Instead you can use:
    If A
for "If true" and use:
    If not(A
for "If not true."
It may not seem like much, but in the end, it will save you a lot of memory.

### Use DelVar

The power of DelVar often goes unrecognized. The following are all legal code using DelVar:
    Delvar ADelVar BDelvar C
    DelVar ADisp B
    Delvar ADelVar B5→C
As you can see, DelVar is a very efficient way to delete variables, as it can also run another command on the same line.
Despite this, there is a catch:
If A=1, it deletes A and then produces a Syntax error, because End is encountered twice. If A=0, nothing happens and the program exits normally because the End after DelVar A is ignored. This is a design flaw in the TI-Basic interpreter.

### Scrollable Lists

Scrollable lists can be quickly created by pausing on a list, for example,
    Pause L1
However, its not the nicest looking layout, so only use it if you need to create a program really fast.

### Pause

On the subject of pause, you can pause on variables, strings, and text, which is convenient.
    Pause A
    Pause Str1
    Pause "My name is David Becker"

### Movement with getKey

Changing the X and Y variables with key presses could be done with four If commands:
This is a better way to do it:

### Ans

If you can, don't place values in variables, but store them in Ans. Ans is a much faster way of storing values, and it won't overwrite any other data. The only bad thing is that if you store a value in variable, Ans is set to that value.
    10
    Disp Ans

### For( trick

You can end a For( loop prematurely by setting the variable it iterates to the end value:
    ClrHome
    1→X
    Disp 2
    Lbl A
    X+2→X
    1→A
    For(Z,3,√(X)) // Here is the For( loop start.
    If not(fPart(X/Z))
    Then
    0→A
    √(X)→Z // This is where the variable is set.
    End
    End // The loop will end here if Z is set to √(X), so the remaining dividers of X are not checked.
    If A
    Disp X
    Goto A

### If trick

You can have these kind of constructions:
    If condition 1
    Then
    code executed if condition 1 is true
    If condition 2
    Else
    code executed if condition 1 is true or if condition 2 is true after the code block is executed
    End
These can save a lot of space in some situations.
Previous: Tips, Tricks and Optimizations Next: Programming Games Table of Contents: TI-Basic Z80 Programming

# Programming Games

It is possible to program simple games using TI-Basic. The explanations for the examples given here are meant to be a simple explanation, not a technical guideline.

## PONG Demonstration

The following program is a simple game of Pong programmed in TI-Basic. We begin by defining the code for the game:
Here, we begin explaining the code:
These first lines initialize variables to certain values. The A and B variables are the coordinates for the ball. C keeps the entire loop running. D and E will change our ball coordinates. They allow us to use more efficient coding than using 1 and -1. F is our horizontal coordinate for the paddle, so that it can move back and forth.
The not( command returns 1 (true) if the conditional is equal to 0. This is equivalent to using While C=0, but reduces a byte.
Refreshes the screen each time something moves (or at least each time the loop repeats).
This prints the symbols to the screen.
This tells the ball to "bounce" off the ceiling by reversing its direction.
This step right here does a bunch of stuff in a little space. The first line checks if the ball is at the bottom of the screen. If the ball is, then it checks if the ball is on the paddle. If the paddle is there, then the ball bounces off.
This tells the ball to bounce off the right and left walls.
This is what triggers the loss. This checks if the ball has hit the bottom of the screen. If it has, then the program terminates the loop.
This step makes the ball move around the screen, by changing the coordinates.
This is what makes the game tick. It is the user input step. getkey→K stores the user keypress into K. Then, in the next line, F (the horizontal coordinate for the paddle) gets one added to it if the user presses ⯈ (26) and is less than 13 (right side of the screen = 16 - 3 (for the size of the paddle))
An equality equation always becomes 1 if it is true, and 0 if false, therefore if it is true, then it will move one in that direction, and if the user presses ⯇ (24) the same principle applies.
This line defines the end of the loop that the main part of the program is running in.
These lines run when you loose. It will display a message, clear the screen, and prevent "Done" from being displayed.
Here is the more optimized version:

### Note

A scoring system and other features can be added, but will be explained in later articles. This program works very well, except that the cursor doesn't move fast enough. In order to make the platform move faster, change:
to:
Which could also be written as the following:
This will make the platform skip over one more space, making the platform faster.
Previous: Advanced Programming Next: List of Commands Table of Contents: TI-Basic Z80 Programming

# Appendix A: List of Commands

TI-Basic Z80 Programming/Appendix A: List of Commands