Coding Cobol: Recursion

You should never, ever write recursive Cobol programs. But recursion is now possible in most Cobol compilers. The following code shows a Cobol program to calculate Fibonacci. A recursive program has two parts: a main program and a “recursive” program (both in the same file). Here is the main program:

identification division.
program-id. fibrecurse.

data division.
working-storage section.
01 n   pic x(4) comp-x.
01 fib pic x(4) comp-x.
01 m   pic x(4) comp-x.

local-storage section.

procedure division.
   display "Nth Fibonacci number? "
   accept n
   call "fibonacci" using by value n returning fib
   display n "th fibonacci = " fib
   goback.
end program fibrecurse.

All the main program does is obtain the user input for the nth Fibonacci number to calculate, and call fibonacci, the recursive “subprogram”. Now onto that subprogram.

identification division.
program-id. fibonacci is recursive.

data division.
local-storage section.
01 result1 usage is binary-long.
01 result2 usage is binary-long.

linkage section.
01 num usage is binary-long.

procedure division using by value num.

   if num equal zero
      move 0 to return-code
      goback
   end-if
   if num = 1
      move 1 to return-code
      goback
   end-if

   compute num = num - 1
   call "fibonacci" using by value num returning result1
   compute num = num - 1
   call "fibonacci" using by value num returning result2
   compute return-code = result1 + result2
   goback.

end program fibonacci.

The linkage section in the “subprogram” associates the variable num, with the variable n in the main program.

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.