CS102 · Annotated SlidesRecursion — Recursion
Recursion · Annotated slides

Recursion

Recursive methods, base cases and recursive cases, countdown, the call sequence, infinite recursion and stack overflow, recursion vs. iteration, tail recursion, factorial, Fibonacci, and a recursive power method.

Slide text Study notes Highlight: key words Tips, tricks & traps Seen again elsewhere How it can come up

Recursion

CS102 · Savitch, Chapter 11
1

Objectives

  • Describe the concept of recursion
  • Use recursion as a programming tool JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
2
Exam weight Low

    Basics of Recursion

    • A recursive algorithm will have one subtask that is a small version of the entire algorithm's task
    • A recursive algorithm contains an invocation of itself
    • Must be defined correctly else algorithm could call itself forever or not at all JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
    3
    Exam weight Low
    1. A recursive method calls itself on a smaller version of the same problem.
    Slide 4: Simple Example - Countdown
    Exam weight Low
    1. First handle the BASE CASE (stopping condition).

    Recursive Countdown

    • Next handle larger cases; phrase solution in terms of a smaller version of the same problem is to output 3 then output
    • countDown(3) the result of countDown(2) View demonstration, listing 11.1 class RecursionCountdown JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
    5
    Exam weight Low

      • See code for count down JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
      6
      Exam weight Low
        Slide 7: Sequence of Calls
        Exam weight Low

          Keys to Successful Recursion

          • Must have a branching statement that leads to different cases
          • One or more of the branches should have a recursive call of the method
            • Recursive call must us "smaller" version of the original argument
          • One or more branches must include no recursive call
            • This is the base or stopping case JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
          8
          Exam weight High
          1. Keys: a branch to separate cases, a recursive call on a SMALLER argument, and a base case with no recursion.
          🎯 How this can come up · 1 question
          Written

          What three things does a correct recursive method need?

          Infinite Recursion

          • Nothing stops the method from repeatedly invoking itself
            • Program will eventually crash when computer exhausts its resources (stack overflow) JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
          9
          Exam weight High
          1. No base case (or not getting smaller) → infinite recursion → StackOverflowError.
          🎯 How this can come up · 1 question
          MCQ

          Infinite recursion in Java eventually causes:

          Slide 10: Recursive Versus Iterative
          Exam weight Low
          1. Every recursive method can be rewritten iteratively.

          Recursive Versus Iterative

          • Recursive method
            • Uses more storage space than iterative version
            • Due to overhead during runtime
            • Also runs slower
          • However in some programming tasks, recursion is a better choice, a more elegant solution JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
          11
          Exam weight Medium
          1. Recursion uses more memory (a stack frame per call) and is often slower; but can be clearer.

          Recursion

          • For some problems, it’s useful to have a method call itself.
          • A method that does so is known as a recursive method.
          • A recursive method can call itself either directly or indirectly through another method. JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
          12
          Exam weight Low

            Recursion

            • Recursion is the process of defining something in terms of itself. As it relates to java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive. JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
            13
            Exam weight Low

              Tail Recursion

              • Tail recursion is defined as occurring when the recursive call is at the end of the recursive instruction. It is useful to notice when ones algorithm uses tail recursion because in such a case, the algorithm can usually be rewritten to use iteration instead. (ex: count Down) JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
              14
              Exam weight Low
              1. Tail recursion: the recursive call is the last action.
              Slide 15: Factorial
              Exam weight Low
                Slide 16: • A recursive declaration of the factorial method is arrived at by observing the
                Exam weight High
                1. n! = n × (n − 1)!, with 0! = 1! = 1.
                🎯 How this can come up · 1 question
                Written

                Write a recursive factorial method.

                • The evaluation of 5! would proceed as shown in Fig. 18.2.

                • Figure 18.2(a) shows how the succession of recursive calls proceeds until 1! (the base case) is evaluated to be 1, which terminates the recursion.
                • Figure 18.2(b) shows the values returned from each recursive call to its caller until the final value is calculated and returned.
                • Figure 18.3 uses recursion to calculate and print the factorials of the integers from 0– 21. JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
                17
                Exam weight Low
                  Slide 18: Slide 18
                  Exam weight Low

                    • The recursive method factorial (lines 7–13) first tests to determine whether a terminating condition (line 9) is true.
                    • If number is less than or equal to 1 (the base case), factorial returns 1, no further recursion is necessary and the method returns.
                    • If number is greater than 1, line 12 expresses the problem as the product of number and a recursive call to factorial evaluating the factorial of number - 1, which is a slightly smaller problem
                    • than the original calculation, factorial(number ). JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
                    19
                    Exam weight Low

                      • See code for factorial JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
                      20
                      Exam weight Low
                        Slide 21: Slide 21
                        Exam weight Low
                          Slide 22: Example Using Recursion: Fibonacci Series
                          Exam weight High
                          1. Fibonacci: 0, 1, 1, 2, 3, 5, 8…; fib(n) = fib(n − 1) + fib(n − 2).
                          🎯 How this can come up · 1 question
                          MCQ

                          With fib(0) = 0 and fib(1) = 1, fib(6) is:

                          Slide 23: 18.4 Example Using Recursion: Fibonacci Series (cont.)
                          Exam weight Low
                          1. Two base cases: fib(0) = 0, fib(1) = 1. Naïve recursion repeats work exponentially.

                          • See code for Fibonacci JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
                          24
                          Exam weight Low

                            JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch

                            © Copyright 1992-2012 by Pearson

                            25
                            Exam weight Low

                              (Recursive power Method)

                              Write a recursive method power(base, exponent) that, when called, returns base

                              exponent

                              For example, power(3,4) = 3 * 3 * 3 * 3.

                              Assume that exponent is an integer greater than or equal to 1.

                              [ Hint: The recursion step should use the relationship

                              exponent = base · base

                              exponent – 1

                              base and the terminating condition occurs when exponent is equal to 1, because

                              1 = base

                              base Incorporate this method into a program that enables the user to enter the base and exponent.]

                              JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch

                              26
                              Exam weight High
                              1. power(base, exp) = base × power(base, exp − 1); power(base, 1) = base.
                              🎯 How this can come up · 1 question
                              Written

                              Write a recursive power(base, exponent).

                              See Code for Pow

                              JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch

                              27
                              Exam weight Low

                                Sample output

                                run:

                                Enter base: 3 Enter exponent: 4 Value is 81 BUILD SUCCESSFUL (total time: 10 seconds)

                                JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch

                                28
                                Exam weight Low

                                  • See code JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
                                  29
                                  Exam weight Low

                                    Summary

                                    • Method with self invocation
                                      • Invocation considered a recursive call
                                    • Recursive calls
                                      • Legal in Java
                                      • Can make some method definitions clearer
                                    • Algorithm with one subtask that is smaller version of entire task
                                      • Algorithm is a recursive method JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch
                                    30
                                    Exam weight Low