Last month we talked about FOR-NEXT loops as a way to repeat steps. This time we’ll look at subroutines, which tell the computer to repeat a series of steps each time you call them.
Subroutines are mini-programs; they execute a series of steps apart from the main program. In essence, you tell the computer, “Go do those steps and then come back here and proceed with the main program.” The ZX80 remembers where it was and returns to the following line after executing the subroutine. You can call the subroutine many times from your main program, but you need type it only once.
Suppose you want to use the TAB subroutine listing on page 17. The subroutine is lines 999-1055, but you need a whole program to fit around it. Say you want to print a list of dollar figures as part of an accounting program you are writing. TAB only helps instruct the computer to display your data in tabular columns. You must still tell what to do with the data you enter. So when you get to line 140, where you want to display results in columns, call up TAB using GO SUB:
:
140 GO SUB 999
:
The computer jumps to 999 and then executes steps until it hits the RETURN command, then hops back to the line after the GO SUB from which it left the main program. When you again want TAB, say at line 290, write:
:
290 GO SUB 999
:
Again, it executes steps 999 to 1055 but this time it returns to the line following 290. TAB uses IF…THEN RETURN statements to jump back. Insert a RETURN at every endpoint of the subroutine.
One more point: As the computer goes through the program steps, it eventually comes to line 999 and tries to carry out the subroutine again. Trouble starts when it prints data you didn’t want and then it hits RETURN and has no where to go. The ZX80 gives you an error code 7, meaning it hit a RETURN with no corresponding GO SUB. To avoid this, insert a jump (GO TO) step:
900 GO TO 2000
999 REM TAB :
1055 GO TO 1030
2000 STOP
Now the machine never runs into the subroutine unless directed there by a GO SUB because the GO TO in 900 causes it to jump over the subroutine to the STOP step.
You can GO SUB backwards and forwards–the ZX80 can jump to a subroutine with a larger or smaller line number, so you can insert your subroutine anywhere in your program. Wherever you put it, remember the GO SUB, RETURN and GO TO steps.
Use subroutines whenever you:
- repeat 3 or more program lines.
- reuse a complex line you might mistype.
- want 2 processing steps to always be identical.