The following sample code illustrates some of the features of a recursive routine. This routine, identified by the entry point factorl, computes the factorial of a number that you enter.
1 working-storage section. 2 01 n pic x(4) comp-x. 3 01 factorial pic x(4) comp-x. 4 01 m pic x(4) comp-x. 5 6 local-storage section. 7 8 procedure division. 9 accept n 10 move 1 to factorial 11 call 'factorl' using n 12 display 'factorial of ' n ' is ' factorial 13 stop run. 14 15 entry 'factorl' using m. 16 if m < 1 17 move 1 to factorial 18 else 19 if m > 1 20 multiply m by factorial 21 subtract 1 from m 22 call 'factorl' using m 23 end-if 24 end-if 25 26 exit program.
local-storage section
Since the recursive routine can be called several times, the local data from one call must be protected from another call to the same code. This protection is done using a Local-Storage Section. Each time a new instance of the routine starts, an initialized copy of this section is created in memory. If you try to use recursion in a program that does not contain a Local-Storage Section, an RTS error message is issued.
Notice that this routine does not have any local storage data items, but it still requires the local storage declaration.
entry 'factorl' using m
This is the entry point of the recursive routine factorl. A program can call itself via its Program-ID or an entry point.
if m > 1
multiply m by factorial
subtract 1 from m
call 'factorl' using m
end-if
This loop contains the recursive call.
call 'factorl' using m
The recursive call statement.