Labels and the GOTO and GOSUB commands
The GOTO and GOSUB commands enable you to jump to certain positions in your program.
Labels are used to specify what point in the program to continue execution.
GOTO
To use GOTO, place a label somewhere in your program, and then enter.
GOTO <label>
Run the following example program:
PRINT "1"
GOTO TheLabel
PRINT "2"
TheLabel:
PRINT "3"
Output (notice how PRINT "2" is skipped):
1
3
Tip: TheLabel can be placed on the same line as PRINT “3”
GOSUB
The GOSUB command is the same as GOTO, except when it encounters a RETURN statement, the program "returns" back to the GOSUB command. In other words, RETURN continues program execution immediately after the previous GOSUB statement.
Run this program:
PRINT "1"
GOSUB TheLabel
PRINT "2"
END
TheLabel:
PRINT "3"
RETURN
(Note: The END command exits the program.)
Since the program returns to the GOSUB command, the number 2 is printed this time.
1
3
2
LINE NUMBERS
"Line numbers" can be used as labels.
PRINT "1"
GOTO 10
PRINT "2"
10 PRINT "3" (Notice the line number)
You can also write the program like this:
10 PRINT "1"
20 GOTO 40
30 PRINT "2"
40 PRINT "3"
The line numbers don't even have to be in sequence.
17 PRINT "1"
2 GOTO 160
701 PRINT "2"
160 PRINT "3"
Each of these programs output:
1
3
Guessing game
The following is a simple guessing game:
CLS
start:
PRINT "Guess a number between 1 and 10: ";
INPUT num
IF (num < 1 OR num > 10) THEN
PRINT "That is not between 1 and 10"
GOTO start
END IF
IF (num = 6) THEN
PRINT "Correct!!!"
ELSE
PRINT "Try again"
PRINT
GOTO start
END IF
Output (may be slightly different):
Guess a number between 1 and 10: ? 2
Try again
Guess a number between 1 and 10: ? 7
Try again
Guess a number between 1 and 10: ? 6
Correct!!!
Tip: Notice the second PRINT statement under PRINT “Try again”, it adds a blank line under Try again when the program is executed.
No comments:
Post a Comment