Section 1.6-While Loops
Section 1.6---While Loops

Back to Home

While loops are commands that aren't used as much as other commands, but are an essential part of programming when you need them. While loops, like their names, repeat themselves as long as the variable equals or does not equal something. Here's an example:
:0->D
:While D=0
:Input "D?",D
:Disp D
:End
This program will keep asking what D is until you enter some number besides 0. How do these help? Well, here we will try writing a program that will show you.
The
Guess
Program
What you have to do is make a program that has a number in mind, and it asks you to guess the number. If you get it right, then it says right, if you don't then it says that you got it wrong, and it asks you until you get the number. This program requires the commands Disp, Input, While, and If-Then. Good Luck
If you're looking for the code for the guess program, here it is:
:15->A
:ClrHome
:0->G
:While G=0
:Input "What is the number?",N
:If N=A
:Then
:Disp "You got it!"
:1->G
:End
:If N>A
:Disp "Too High"
:If N (is greater than) A
:Disp "Too Low"
:End

That was it. You might ask "What the heck is going on with the variable G and the While loop? It's what makes the program ask you again if you get it wrong. G is whether you have guessed the number or not. If you haven't, it's 0, and if you have, it's 1. While you haven't guessed the number (G=0), then ask for the number and tell whether it's right or wrong. After you guess it, G is set equal to 1, and since G no longer equals 0, it ends the while loop, thus ending the program. You will be faced with problems like these all the time when programming. It takes a good knowledge of the commands you have avalible to you and a knowledge of how to use theses commands. Don't be afraid to experiment! That's the best way to learn the feel for the programming language. If you did good on this program, you'll do well on others. If you didn't play around with the language a bit to get a feel for the commands and how they work.
One last thing before you move on. What if you want the number to change every time? There's a function that makes a random number. Press [MATH],[Right Arrow],[Right Arrow],[Right Arrow],[5] to get the randInt( function. In the parenthesis, type a range (for this program, 1 to 100 is good). In the guess program, in place of 15->A, Put the function randInt(1,100)->A.

Section 1.7--The getKey command