This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Discussion 3A Notes (Week 5, February 6) TA: Brian Choi ([email protected] ) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Recursion A recursion is a functionwriting technique where the function refers to itself . Because lectures must have covered the concept of recursion sufficiently, we’ll focus mostly on the tricks in writing a recursive function. The Way to Think About Recursion Writing a recursive function involves the division of a problem into subproblems. A good example is the factorial function that computes n! = n x (n1) x (n2) x ... x 2 x 1 for some arbitrary n ≥ . Here is the iterative way of writing factorial : Iterative functions are more intuitive than recursive functions because we can see the whole process  you see how factorial goes from 1 to n and multiply them up. When writing the recursive version of the same function, you need not worry about “going from 1 to n .” Instead, we only worry about “going from n1 to n .” Believe factorial(n1) will return the right value! This is the “subproblem” we need to solve. In factorial ’s case, if you know the value of factorial(n1) , it is very easy to compute factorial(n) we only need to multiply n to the value of factorial(n1) (because n*factorial(n1) = n*{(n1)*(n2)*...*2*1} = factorial(n) ). This is what’s meant by “going from n1 to n .” Translating this into a C++ code, we get the following function: My factorial function on the left will simply assume that factorial(n1) will return what we want, and compute the value of factorial(n) based on this assumption. When factorial(n1) is called, then it will make the same assumption and will use the value of factorial(n2) to compute its value, ... , and so on. For example, if factorial(5) is called, it will rely on the value factorial(4) returns. When factorial(4) is called, it will rely on the value factorial(3) returns. When factorial(3) is called, it will rely on the value factorial(2) ... Wait, there is something wrong here. We seem to be stuck in an infinite recursion. We need an end to this....
View
Full
Document
This note was uploaded on 11/07/2009 for the course CS 32 taught by Professor Davidsmallberg during the Winter '08 term at UCLA.
 Winter '08
 DavidSmallBerg
 Recursion

Click to edit the document details