Recursion Flashcards
what is recursion
when a function calls itself
this produces repetition
when is recursion used
to make code repeat
as an alternative to iteration
what are the advantages and limitations of recursion
+ shorter and simpler code
- each recursion uses up space in memory
structure of a recursive function
- header w/ name of func and parameters
- base case - an if statement, ends as the final return
- the name of the function itself with any other parameters
the base case
an if statement
typically at the top of a recursive function defenition
if the test is true , the recursion stops
how are parameters used in recursuon
pass values along the chain of functions that open in memory
how to convert a recursive function to iteration
- turn the if line of the base case into the header of a while loop, reversing the logic
- indent the commands inside the while loop
- delete recursive lines
how to convert an iterative function to recursion
- convert the header of the while loop into a base case (if statement) , reversing the logic
add a recursive line at the end of the program
consider whether you need to use parameters
similarity between recursion and iteration
used to repeat blocks of code
differences between recursion and iteration
recursive function often solves a problem in fewer lines of code, but uses more memory
iterative function overrwrites same area of memory repeatedly, using less space
iterative functions use more lines to solve the problem