So far we've used GOTO to repeat parts of a program, but an earlier section mentioned that we can use it to skip ahead as well. The IF statement, even if it has a chain of IF commands, allows only one final statement to be conditionally executed. Sometimes we want several different things to be done based on a condition; it would be cumbersome to have to repeat the IF command for each of those things:
10 LET P=50 20 PRINT "Tax code? 0=none, 1=20%" 30 INPUT T 40 IF T=1 THEN PRINT "Adding 20% tax." 50 IF T=1 THEN LET P=P+(P*20/100) 60 PRINT "Price: ",P
This calculates the tax-inclusive price of something whose tax-exclusive price is 50. If the user specifies a tax code of 1, the program does two things: prints a message that it is adding the tax, then adds it. The following version of the program is more elegant, as it has to check the tax code only once:
10 LET P=50 20 PRINT "Taxable? 1=YES, 0=NO" 30 INPUT T 35 IF T=0 THEN GOTO 60 40 PRINT "Adding 20% tax." 50 LET P=P+(P*20/100) 60 PRINT "Price: ",P
We're not saving much here, and adding an extra line, but you can imagine that the saving becomes significant if there are five or ten things we want to do for a tax code of 1.
Tiny BASIC does have a trick with GOTO that some more powerful BASIC languages lack: the computed GOTO. Instead of specifying a set line label for GOTO, you can calculate one. Here's a trivial game that asks a player to select one of three boxes, then tells them what their prize is:
10 PRINT "Which box (1-3)?" 20 INPUT B 30 IF B<1 THEN GOTO 10 40 IF B>3 THEN GOTO 10 50 GOTO 50+10*B 60 PRINT "You win nothing. Try again." 65 GOTO 10 70 PRINT "You win a wooden spoon. Try again." 75 GOTO 10 80 PRINT "You win a bag of gold!"
The GOTO in line 50 features an expression that calculates a value based on B: for B=1 the result is 60, for B=2 it's 70, and for B=3 it's 80.
Next: More Ways to Control Program Flow