24
CipherLab BASIC Programming Part I
A subroutine is a set of instructions given a particular name or a line label. Users can
simplify their programming by breaking programs into smaller logical subroutines. A
subroutine will be executed when being called by a GOSUB command. For example,
ON KEY(1)GOSUB KeyF1
…
KeyF1:
PRINT “F1 is pressed.”
RETURN
The command RETURN marks the end of the subroutine and tells the processor to return
to the caller. A subroutine has to be appended at the end of the main BASIC program.
A subroutine can be defined with or without a pair of brackets. For example,
SUB Subroutine1( )
…
PRINT “Subroutine1 is executed.”
END SUB
…
SUB Subroutine2
…
PRINT “Subroutine2 is executed.”
END SUB
Since all the variables in the CipherLab BASIC program are treated as global variables,
passing arguments to subroutines is meaningless and enclosing arguments in the
brackets of the subroutines will lead to a syntax error while compiling.
A subroutine in BASIC can be recursive, which means it can call itself or other
subroutines that in turn call the first subroutine. The following sample program contains
a recursive subroutine – Factorial, to calculate the value of n! (“n factorial”).
PRINT “Please enter a number (1 – 13):”
INPUT N%
FactResult! = 1
Fact% = N%
GOSUB Factorial
PRINT N%, “! = ”, FactResult