Recursion

Recursion - . CHAPTER 2 Recusior! A recursive function is...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CHAPTER 2 Recusior! . Two functions A and B are munrally recunive, if A calls B ard B calls A. . Recursion can always replace iterdion (loopitrg). DEFINITION OF n! I if n=0 Factorir{r1) = n' Factorial(n- l) ifn>0 This rccrtrsive defmition screarns for a recr.[sive implemeDtatioD. . A recursive function is a fu{ction that calls iisetf n! . Fctorial(0) = 1 (By definition) Fetorial(l) = I Factorial(2) - 2* I Fatorial(3) = 3*2* 1 Fetorial(4) = 4+3*2*1 Frctoriaqn; =1* o-1 *^-2t ...1 4 irlt fa.todal (ht D) { if (n-=0) retum 1; €lse retum n* fetorial(rl - l); )
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
IIow to udderstrnd recursion: Every time a recursiv€ fungtion is called, that's like it is a oomplctely separale functior- Just ignore the fact that this function was called by itseli Specifically, if'factorial" ca.lls itseq then there ar€ two param€ters "n" that have NOTHING to do with each other. factorial(2) .etums 2 to factorial(3). lnsido factorial(3 ), 3 * factorial(2) becomes: 3 * 2 So, inside factorial(3), lie retum valu€ is 3 * 2 = 6. This is what will be rctumedto the program. cout << factorial(3) ; // writes 6 to the screen. factorial(3): n=3 calls fotorial(2) fatorial(2): n-2 calls factorial( l) factorial(l): r: I calls faotorial(0) faclorial(0)i retums I to factorial(l). Inside factorial(l ), I * factorial(0) becomes: I * I factorial(I): retums I to factorial(2), Inside faaorial(2), 2 * factorial( l) becomes: 2* I A problem can be solved recursively ifthe lbllowing conditions are t'ulfi lled: I - The probleD ca be decomposcd jnto scvc.al problems such that (al leasr) one otrhem is of lh. sm€ kind" as lhe inilial p.oblcm but ''simpl€r" dd sli ihe ot}ere s€ -esll I - factorial(n) is decomposed into two problems: A multiplication and factorial(D-l) is a problem ofthe same kind as factorial(n), but factorial(n- I ) is also simpler ften frctcri al(n). 2- Ifwe keep reducing dle agurnent of factorial( ) more and more, eventual$, $e $ill get factorial(0) which is "easy ' to solve- 2 - If you koep derivilg simpler and simpler problems ofthe " same khd", you will eventually r€ach
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This document was uploaded on 02/02/2010.

Page1 / 8

Recursion - . CHAPTER 2 Recusior! A recursive function is...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online