Recursion in COBOL

Our example demonstrates recursive functions in COBOL. Here’s a classic example.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. RECURSION-EXAMPLE.
       
       ENVIRONMENT DIVISION.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-RESULT PIC 9(10).
       
       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           CALL 'FACT' USING BY CONTENT 7 
                             BY REFERENCE WS-RESULT.
           DISPLAY 'Factorial of 7: ' WS-RESULT.
           
           CALL 'FIB' USING BY CONTENT 7 
                            BY REFERENCE WS-RESULT.
           DISPLAY 'Fibonacci of 7: ' WS-RESULT.
           
           STOP RUN.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. FACT RECURSIVE.
       
       DATA DIVISION.
       LINKAGE SECTION.
       01 LS-N PIC 9(5).
       01 LS-RESULT PIC 9(10).
       
       PROCEDURE DIVISION USING LS-N, LS-RESULT.
           IF LS-N = 0
               MOVE 1 TO LS-RESULT
           ELSE
               SUBTRACT 1 FROM LS-N GIVING LS-N
               CALL 'FACT' USING BY CONTENT LS-N 
                                 BY REFERENCE LS-RESULT
               MULTIPLY LS-N BY LS-RESULT GIVING LS-RESULT
           END-IF.
           EXIT PROGRAM.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. FIB RECURSIVE.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-FIB1 PIC 9(10).
       01 WS-FIB2 PIC 9(10).
       LINKAGE SECTION.
       01 LS-N PIC 9(5).
       01 LS-RESULT PIC 9(10).
       
       PROCEDURE DIVISION USING LS-N, LS-RESULT.
           IF LS-N < 2
               MOVE LS-N TO LS-RESULT
           ELSE
               SUBTRACT 1 FROM LS-N GIVING LS-N
               CALL 'FIB' USING BY CONTENT LS-N 
                                BY REFERENCE WS-FIB1
               SUBTRACT 1 FROM LS-N GIVING LS-N
               CALL 'FIB' USING BY CONTENT LS-N 
                                BY REFERENCE WS-FIB2
               ADD WS-FIB1 TO WS-FIB2 GIVING LS-RESULT
           END-IF.
           EXIT PROGRAM.

This FACT function calls itself until it reaches the base case of FACT(0).

In COBOL, we define recursive functions by using the RECURSIVE keyword in the PROGRAM-ID paragraph. The FACT function is defined this way.

For the Fibonacci sequence, we’ve created a separate recursive function FIB. In COBOL, we can’t define closures like in some other languages, so we use a separate subprogram.

To run the program, compile the COBOL code and execute it:

$ cobc -x recursion-example.cob
$ ./recursion-example
Factorial of 7: 5040
Fibonacci of 7: 13

This example demonstrates how to implement recursive functions in COBOL, which is less common but still possible in the language. The syntax and structure are quite different from more modern languages, reflecting COBOL’s unique approach to program organization and data handling.