Dear Citizens of the World,
We went over more examples of Recursive Functions this week, including a bit on Tracing Recursive Functions Using Stacks and Recursive Structures.
Pretty much a recursive function is a function which uses itself in its body, which at first sounds weird. When I looked at it at first I got confused, but it's actually not that complicated. The fact that a recursive function has a base case helps a ton and makes the process of calculating so much more sensible, and, in turn, easier! :D
Example of Recursive Functions:
Unicorn(n) = 2n * Unicorn(n - 1)
Unicorn(0) = 2
Notice how the function is calculated using the function itself?
A recursive function must have minimum one base case, and minimum one recursive case.
In the above example:
Base case -> Unicorn(0) = 2
Recursive case -> Unicorn(n - 1)
The base case saves the day, because if we expand the whole entire process we get:
Say n = 2:
Then,
Unicorn(2) = 2(2) * Unicorn(1)
= 4 * (2(1) * Unicorn(0)
= 4 * (2 * 2)
= 4 * (4)
= 16
If we didn't have a base case, we wouldn't be able to calculate the answer to Unicorn(2). We would simply expand the function until we couldn't any longer, which wouldn't help us at all. :P
General Form of Recursion:
if (something that allows us to detect a base case):
(Apply something that does not use recursion)
else:
(A generalized case)
(Apply something that does involve recursion)
I'm still attempting to understand the rest, but until then this is all I have, my apologies. :(
I'll update as soon as I do!
Peace out! :)
No comments:
Post a Comment