PencilCoder

Recursion!

Goals:

  • Use recursion to repeat code blocks without using iteration

Coding Snippets:

  • coding snippets
  • Recursion occurs when a function calls itself, directly or indirectly, one or more times, until a specified condition (the base case) is met.
  • In the example, the recursive call is indirect: askQuestion invokes the read function, which calls the callback cb, which in turn may recursively call askQuestion. This process continues until the user enters yes.

Math and Computer Concepts:

  • Using recursion, we can sometimes write very short and conceptually straightforward code that accomplishes the same result as a much longer or more complicated script involving iteration (i.e., with a for or while loop).
  • Recursion provides an alternative to iteration, but it is not always preferable. For example, recursive algorithms may be less efficient than iterative alternatives. Moreover, recursive algorithms can sometimes be very difficult to comprehend.

Activities:

Save each of the following in a folder called Recursion.