The Rogue's
TI-86 BASIC Tutorial
~
Chapter 5: Loops

Loops are an extremely important part of any programming language. They allow you to repeat blocks of code more than once, or until certain conditions are true.

For( Loops: A For( loop takes a variable, changes its value (By adding to or subtracting from it), and repeats until a condition is true. The syntax of a for loop is "For([variablename],[beginnumber],[endnumber],[increment]". [variablename] is the name of the variable, [beginnumber] is the value that the variable starts at, [endnumber] is the number after which the loop quits, and [increment] is how much the variable is changed by each cycle of the loop. So, say you wanted to make variable A change from 1 to 10 counting by 1. Make a new program called "FORLOOP" and enter this:

:For(A,1,10,1
:Disp A
:End

This is like saying, "Store 1 to A, display A, go back and store 2 to A, display A, go back and store 3 to A, display A, and repeat this process over and over until A=10". Run the program. It should rapidly display the numbers 1 to 10. Now let's rewrite the code to count down from 10 to 1:

:For(A,10,1,-1
:Disp A
:End

Run the program. It might not seem like much right now, but For( loops are extremely powerful and versatile. If you want the for loop to increment by 1, like in the first sample code, you can save space by leaving off the increment (because 1 is the default) like this:

:For(A,1,10
:Disp A
:End

You can also use a for loop to repeat code a set number of times. If you want to display "Hello" 3 times, you would simply enter this:

:For(A,1,3
:Disp "Hello"
:End

Basically, A is counting from 1 to 3, and each time the loop repeats it displays "Hello". Neat. Familiarize yourself with this important command.

While Loops: A while loop repeats code as long as a condition is true. The syntax is "While [condition]". An example of a condition is "A<5". Put this code into a program called "WHYLOOP":

:0->A :While A<5
:ClLCD
:Disp "Enter a number","greater than 5:"
:Prompt A
:End

As long as A is less than 5, the program will repeatedly ask the user to enter a number greater than 5. So, if the user enters the number 3 (Which, of course, is less than 5), the program will ask for a number greater than 5 again. Expiriment with the While loop before continuing.

Repeat Loops: The repeat loop is the exact opposite of the While loop. It repeats a block of code until a condition is true. So, if this code were entered...

:8->A :Repeat A<5
:ClLCD
:Disp "Enter a number","less than 5:"
:Prompt A
:End

...then the loop would be executed over and over until the value of A is less than 5.


If you understand everything on this page, you are ready for Chapter 6: Graphics.

Click to Return to This Tutorial's Home Page