Site hosted by Angelfire.com: Build your free website today!

Reinier's QBasic page: Lesson 3: GOTO and GOSUB

GOTO and GOSUB cause the program to jump to another line and go on from there, which is often helpful.
GOTO line number
This simply causes the program to continue from that line number, whether it's before or after the current line.

Example:
10 PRINT "Reinier"
20 GOTO 40
30 PRINT "QBasic"
40 PRINT "programs"

Output:
Reinier
programs

The program skips from 20 to 40, skipping 30 completely.


GOSUB line number
Jumps to another line and continues the program from there until it comes across RETURN, after which it returns to the line after GOSUB.

Example:
10 PRINT "Reinier is";
20 GOSUB 50
30 PRINT "years old."
40 END
50 A=13
60 PRINT A;
70 RETURN

Output:
Reinier is 13 years old.

Note: The program is for illustration of GOSUB only. The program can be written in a much easier way.

The program does line 10, then in line 20 it jumps to 50. The program executes the lines thereafter until it hits RETURN, and it returns to the line after GOSUB, which is 40. The program ends there, because of END.


{GOTO|GOSUB} label
The program jumps to the label, exactly as a line number. This is for people who are really paranoid about not using line numbers :-)

Example:
PRINT "Reinier"
GOTO Line
PRINT "QBasic"
Line:
PRINT "program"

Output:
Reinier
program

GOSUB works the same way.


Return to lessons
Return home