Recursion
Recursion
Chapter 6
Recursion
Objectives
• Infinite recursion
– Occurs if every recursive call results in another
recursive call
– Executes forever (in theory)
– Call requirements for recursive functions
• System memory for local variables and formal
parameters
• Saving information for transfer back to right caller
– Finite system memory leads to
• Execution until system runs out of memory
• Abnormal termination of infinite recursive function
Data Structures Using C++ 2E 9
Recursive Definitions (cont’d.)
• maximum(list[0],
largest(list[1]...list[5]))
• maximum(list[1],
largest(list[2]...list[5]), etc.
• Every time previous formula used to find largest
element in a sublist
– Length of sublist in next call reduced by one
• Function reversePrint
– Given list pointer, prints list elements in reverse order
• Figure 6-5 example
– Links in one direction
– Cannot traverse backward starting from last node
• Object
– Move 64 disks from first needle to third needle
• Rules
– Only one disk can be moved at a time
– Removed disk must be placed on one of the needles
– A larger disk cannot be placed on top of a smaller disk
• Recursive algorithm
– Start at first row and find empty slot
– Find first number to place in this slot
– Find next empty slot, try to place a number in that slot
– Backtrack if necessary; place different number
– No solution if no number can be placed in slot