Subroutines are a way for you to have a chunk of code that can be “called” more than once within your program. You usually use it if you’ve got a block of a few lines of code repeated more than once within your listing. We use the commands GO SUB (GO to SUBroutine) and RETURN (RETURN from subroutine).

Take the following code as an example:

10 LET A = 5
20 LET B = 6
30 LET C = 100
40 GO SUB 9000
50 LET A = 100
60 LET B = 200
70 LET C = 300
80 GO SUB 9000
8998 STOP
8999 REM START OF SUBROUTINE AREA
9000 REM Subroutine to calculate the average of A, B and C
9010 LET R = (A+B+C)/3
9020 PRINT "The average of "; A; ","; B; " and "; C; " is "; R
9030 RETURN

The code at lines 9000-9030 are the subroutine; this subroutine calculates the average of A, B and C and prints the results. The code from 10 to 40 set those variables up and calls the subroutine; this calculates and outputs the result. Line 120 will then return program execution back to the line immediately after the GO SUB, in this instance line 50.

This is then repeated again (lines 50 to 80) with different values for A, B and C. Note the STOP command in line 8998; this is important. If the STOP command is omitted then the code will run into the subroutines.

You can see that GO SUB is very similar to GO TO; the only difference is that GO SUB pushes the line number onto the stack before it starts executing the subroutine; the RETURN instruction fetches this instruction back off the stack and continues execution from that point.

It was common practice to give all the subroutines high line numbers (I used to start at 9000). If I needed to add a second subroutine to this program, I’d probably start it at line 9100, just in case I needed to add any lines to the subroutine above it. It can be a real pain renumbering all your GO SUBs so it’s good to put some thought into this whilst writing the program.

A subroutine can call other subroutines, or indeed itself (a technique called recursion).