Code the RECURSIVE clause on the PROGRAM-ID clause so your program can be recursively reentered while a previous invocation is still active. Below is an example of how you could use the RECURSIVE clause to make a program a recursive program, and how a Local-Storage Section data item can be used in a recursive program.
Figure 53. Example of a recursive call to calculate the factorial of a number
5722WDS V5R3M0 030905 LN IBM ILE COBOL MYLIB/FACTORIAL ISERIES 03/09/15 17:25:51 Page 2 S o u r c e STMT PL SEQNBR -A 1 B..+....2....+....3....+....4....+....5....+....6....+....7..IDENTFCN S COPYNAME CHG DATE 1 000100 IDENTIFICATION DIVISION. 2 000200 PROGRAM-ID. FACTORIAL RECURSIVE. 000300 3 000400 ENVIRONMENT DIVISION. 4 000500 CONFIGURATION SECTION. 5 000600 SOURCE-COMPUTER. IBM-ISERIES. 6 000700 OBJECT-COMPUTER. IBM-ISERIES. 000800 7 000900 DATA DIVISION. 8 001000 WORKING-STORAGE SECTION. 9 001100 01 NUMB PIC 9(4) VALUE 5. 10 001200 01 FACT PIC 9(8) VALUE 0. 001300 11 001400 LOCAL-STORAGE SECTION. 12 001500 01 NUM PIC 9(4). 001600 13 001700 PROCEDURE DIVISION. 14 001800 MOVE NUMB TO NUM. 15 001900 IF NUMB = 0 16 002000 MOVE 1 TO FACT 002100 ELSE 17 002200 SUBTRACT 1 FROM NUMB 18 002300 CALL "FACTORIAL" 19 002400 MULTIPLY NUM BY FACT 002500 END-IF. 20 002600 DISPLAY NUM "! = " FACT. 21 002700 GOBACK. 22 002800 END PROGRAM FACTORIAL. * * * * * E N D O F S O U R C E * * * * * |
(C) Copyright IBM Corporation 1992, 2005. All Rights Reserved.