Example: storage sections

The following example is a recursive program that uses both WORKING-STORAGE and LOCAL-STORAGE.


CBL pgmn(lu)
*********************************
* Recursive Program - Factorials
*********************************
 IDENTIFICATION DIVISION.
 Program-Id. factorial recursive.
 ENVIRONMENT DIVISION.
 DATA DIVISION.
 WORKING-STORAGE SECTION.
 01  numb  pic 9(4)  value 5.
 01  fact  pic 9(8)  value 0.
 LOCAL-STORAGE SECTION.
 01  num  pic 9(4).
 PROCEDURE DIVISION.
     move numb to num.

     if numb = 0
        move 1 to fact
     else
        subtract 1 from numb
        call 'factorial'
        multiply num by fact
     end-if.

     display num '! = ' fact.
     goback.
 End Program factorial.

The program produces the following output:


0000! = 00000001
0001! = 00000001
0002! = 00000002
0003! = 00000006
0004! = 00000024
0005! = 00000120

The following tables show the changing values of the data items in LOCAL-STORAGE and WORKING-STORAGE in the successive recursive calls of the program, and in the ensuing gobacks. During the gobacks, fact progressively accumulates the value of 5! (five factorial).

Recursive calls Value for num in LOCAL-STORAGE Value for numb in WORKING-STORAGE Value for fact in WORKING-STORAGE
Main 5 5 0
1 4 4 0
2 3 3 0
3 2 2 0
4 1 1 0
5 0 0 0

 

Gobacks Value for num in LOCAL-STORAGE Value for numb in WORKING-STORAGE Value for fact in WORKING-STORAGE
5 0 0 1
4 1 0 1
3 2 0 2
2 3 0 6
1 4 0 24
Main 5 0 120