11.5 Recursion vs. Iteration

  • Both iteration and recursion are based on a control statement
    • Iteration uses an iteration statement
    • Recursion uses a selection statement
  • Both involve iteration
    • Iteration explicitly uses an iteration statement
    • Recursion achieves iteration through repeated function calls
  • Both involve a termination test
    • Iteration terminates when the loop-continuation condition fails
    • Recursion terminates when a base case is reached
  • Both gradually approach termination
  • Both can occur infinitely
    • An infinite loop occurs with iteration if the loop-continuation test never becomes false
    • Infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on the base case, or if the base case is mistakenly not tested

Negatives of Recursion

  • Recursion repeatedly invokes the mechanism, and consequently the overhead, of function calls
  • Can be expensive in terms of both processor time and memory space
  • Each recursive call causes another copy of the function’s variables to be stored in the stack frame
    • Can consume considerable memory space
  • Iteration avoids these repeated function calls and extra memory assignments
  • However, for some algorithms that are easily expressed and understood with recursion, iterative solutions are not readily apparent

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.