HP 3000 Manuals

Recursion [ Micro Focus COBOL for UNIX COBOL User Guide ] MPE/iX 5.0 Documentation


Micro Focus COBOL for UNIX COBOL User Guide

Recursion 

This section shows you how you can create recursive programs with this
COBOL system.

In this COBOL system, a program can be recursive provided it is not
nested inside another program and it has a Local-Storage Section.  A
program can call itself via either its Program-ID or an entry point.  The
example below illustrates recursion in COBOL. It reads a table of a
person's descendants and displays the names of those who have no
children.

Each call of a recursive routine is called an 
instance.  Each instance needs a different set of the data items used by
the routine.  For this reason this COBOL system enables you to have a 
Local-Storage Section.  Every time a new instance of the routine starts,
a new copy of this section is created in memory; this is deleted when the
instance finishes.  You get a run-time error message if you try to use
recursion in a program that does not contain a Local-Storage Section.

Example 

In the following example, the table in the item family-tree contains an
entry for each of Fred Smith's descendants.  Assume the data has been put
in the table by an earlier program.  The first entry is Fred Smith's own.
Each entry contains, as well as the person's name, a data item called
eldest-pointer containing the position in the table of the entry for that
person's eldest child.  Someone with no children has 99 in this item.
Similarly each entry has a data item sibling-pointer pointing to the
entry for the person's next younger sibling.  Someone with no younger
siblings has 99 in this item.

      identification division.
      program-id. family.
         . . .
      working-storage section.
      01 family-tree.
          03 individual     occurs 50.
              05 ind-name           pic x(30).
              05 eldest-pointer     pic x comp-5.
              05 sibling-pointer    pic x comp-5.

      local-storage section.
      01 tree-pointer               pic x comp-5.

      linkage section.
      01 parent-pointer             pic x comp-5.
      procedure division.
          move 1 to tree-pointer
          call "children" using tree-pointer
          stop run.

     * If this person has no eldest child, routine "children"
     * displays the person's name and does nothing more. Otherwise,
     * this routine starts with the person's eldest child and calls
     * itself for each sibling in turn.

      entry "children" using parent-pointer.
          move eldest-pointer(parent-pointer) to tree-pointer
          if tree-pointer = 99
              display ind-name(parent-pointer)
          else
              perform until tree-pointer = 99
                  call "children" using tree-pointer
                  move sibling-pointer(tree-pointer)to tree-pointer
              end-perform
          end-if.



MPE/iX 5.0 Documentation