再帰の例

次の例では、項目 family-tree の表に Fred Smith の子孫 1 人につき 1 つの項が含まれています。データは、事前に他のプログラムにより表に入力されているとします。最初の項は Fred Smith 自身の項です。各項には、各人の名前とともに、eldest-pointer というデータ項目があり、その人の長子の項の表内での位置が含まれます。子供がいない場合、この項目の値は 99 です。同様に、各項には sibling-pointer というデータ項目があり、その人の弟または妹の項を示します。弟または妹がいない場合、この項目の値は 99 です。

次に、再帰を使用して家系図を検索する例を示します。

 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.