{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Lecture 4 - CHAPTER 2 A recursive function is a function...

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

View Full Document Right Arrow Icon
1 CHAPTER 2 Recursion 2 • A recursive function is a function that calls itself. 3 • Two functions A and B are mutually recursive, if A calls B and B calls A. • Recursion can always replace iteration (looping). 4 n! • A simple example: Factorial. Factorial(0) = 1 (By definition) Factorial(1) = 1 Factorial(2) = 2*1 Factorial(3) = 3*2*1 Factorial(4) = 4*3*2*1 Factorial(5) = 5*4*3*2*1 Factorial(n) = n * n-1 * n-2 * ... 1 5 DEFINITION OF n! 1 if n = 0 Factorial(n) = n * Factorial(n-1) if n > 0 This recursive definition screams for a recursive implementation . 6 int factorial (int n) { if (n = = 0) return 1; else return n * factorial(n - 1); }
Image of page 1

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

View Full Document Right Arrow Icon
7 How to understand recursion: Every time a recursive function is called, that’s like it is a completely separate function. Just ignore the fact that this function was called by itself. Specifically, if “factorial” calls itself, then there are two parameters “n” that have NOTHING to do with each other. 8 factorial(3): n = 3 calls factorial(2) factorial(2): n = 2 calls factorial(1) factorial(1): n = 1 calls factorial(0) factorial(0): returns 1 to factorial(1). Inside factorial(1), 1 * factorial(0) becomes: 1 * 1 factorial(1):
Image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern