Previous Topic Next topic Print topic


Example of Recursion

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.

An example that shows how to use recursion to search a family tree:

 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 9(2).
         05  sibling-pointer    pic 9(2).

 local-storage section.
 01  tree-pointer      pic 9(2).

 linkage section.
 01  parent-pointer    pic 9(2).

 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.
Previous Topic Next topic Print topic