Our example demonstrates recursive functions in COBOL. Here’s a classic example.
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:
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.