Home Previous section Next section

Labels and the GOTO and GOSUB commands Star


The GOTO and GOSUB commands enables 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"

TheLabel: 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.

    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.



Next section


Feel free to distribute this tutorial, upload it to your website, link to it from your site, etc.

http://www.geocities.com/progsharehouse/qbtutor
Mirror: http://development.freeservers.com/qbtutor