Recursion!
Goals:
- Use recursion to repeat code blocks without using iteration
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 theread
function, which calls the callbackcb
, which in turn may recursively callaskQuestion
. 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
orwhile
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.
RecursiveSquare: Recursion offers an alternative to iteration. Explore this fact by coding a recursive function that draws a square. Once you've got this in hand, consider using it to draw other designs, such as a spirograph—naturally, also using recursion!
- CountdownCountup: Explore the importance of the placement of the recursive function call by coding two very similar functions,
countDown
andcountUp
. Both functions should take a single integer argument that specifies the number to count down or up to. The former should make calls tolabel
, to print values to the screen, prior to the recursive function call, whereas the latter should include calls tolabel
subsequent to the recursive call. - BacktrackSpiral: Code a recursive
squiral
function to instruct the turtle to draw from the outside in, stopping at a logical base case and then reverses to retrace its steps to the starting point. Use recursion to code a Tree. Define a function
tree
that takes a single argument, denoting a length. If the value is positive, draw a branch based on that length. With the turtle at the end of that branch, then recursively calltree
with a smaller argument to (potentially) draw two more branches.