13A: Recursion

What We Will Cover


Continuations

Questions on What's Due Next?

Questions from last class?

13.1: Recursive Thinking

Objectives

At the end of the lesson the student will be able to:

  • Explain the underlying concepts of recursion
  • Define infinite recursion and discuss how to avoid it

"To understand recursion, one must first understand recursion."
-- Unknown

13.1.1: Recursive Definitions

Recursion: when an algorithm is defined in terms of itself.

  • Recursion is a natural approach to some problems
  • Allows us to break down a problem into one or more subproblems similar in form to the original problem
    • Sounds circular, but in practice is not
  • For example, suppose we wanted to defined a list of numbers separated by commas
  • We can define this list recursively as:
  • A List is a: number
           or a: number comma List
    
  • Examples of a List include:
  • 10
    21, 6, 54, 7, 19
    10, 11, 15
    
  • No matter how long the list is, the recursive definition describes it
  • List of one element, like the first example, is covered by the first rule
  • Lists longer than one number are covered by the second rule
  • Second rule is known as the recursive part
  • Used as many times as needed until the last element is reached
  • Last element is always defined by the non-recursive part, known as the base case

13.1.2: Infinite Recursion

  • Note that the definition of a List has two parts
    • One option is not recursive
    • One option is recursive
  • Recursion always divides the problem into two parts:
    • Base case
    • Simpler problem
  • Simpler problem divides the problem again until solvable with the base case
  • Must eventually terminate with the base case
  • If only the recursive case was used, the definition would never end
    • Known as infinite recursion
    • Similar to infinite loops

13.1.3: Recursion in Math

  • Math has many instances of recursion
  • One classic example is n!, pronounced n-factorial
  • The factorial n! is defined for a positive integer n as:

When n = 0

n! = 1

And for values of n greater than 0:

n! = n * (n-1) * (n-2) * (n-3) * ... * 1

For Example

  • 3! is defined as:
  • 3! = 3 *  2 * 1 = 6
  • 5! is defined as:
  • 5! = 5 * 4 * 3 *  2 * 1 = 120

Another Notation

  • Another notation for the factorial definition is:
  • N(x) = x * N(x - 1)
    N(0) = 1
    
  • Symbol x represents the current factorial number
  • N(x) represents the accumulated value

Further Information

13.1.4: Summary

  • Recursion is when an algorithm is defined in terms of itself
  • Allows us to define subproblems in similar form to the original
  • Recursion always has two parts:
    • Base case
    • A problem that is closer to the solution
  • Eventually, the base case is always called
  • Without the base case, you would have infinite recursion

Exercise 13.1

Use the next 5 minutes to complete the following exercises and answer any questions. We will discuss the questions after the time has elapsed.

Exercises

  1. What is recursion?
  2. When is a base case necessary for recursive definitions?
  3. Write a recursive definition of i * j, when i > 0. Define the multiplication process in terms of integer addition.
  4. Examples of integer multiplication:

    2 * 3 = 3 + 3 = 6
    4 * 7 = 7 + 7 + 7 + 7 = 28
    

13.2: Recursive Programming

Objectives

At the end of the lesson the student will be able to:

  • Define recursive methods
  • Trace the processing steps of recursive methods
  • Explain when to use recursion and when to use iteration

13.2.1: Writing Recursive Methods

  • Recursive methods implement recursive algorithms
  • Methods call themselves either directly, or indirectly through another method
  • General form of recursive methods:
  • returnValue recursiveMethod(arguments) {
        If (stopping condition) { // base case
            /* do whatever at the end */;
        } else {
            //execute recursive step
            recursiveMethod(arguments);
        }
    }
    
  • Recursive methods must eventually terminate
  • Must have at least one base, or stopping, case.
  • A base case does not execute a recursive call.

  • Base case used to stop the recursion
  • Each successive call to a method must be a "smaller version of itself" so that a base case is eventually reached

13.2.2: Example: Sum

  • Consider the problem of summing the values between 1 and n
    • Where n is any positive number
  • We start our analysis by looking at a few examples:
  • S(1) = 1
    S(2) = 2 + 1 = 3
    S(3) = 3 + 2 + 1 = 6
    S(4) = 4 + 3 + 2 + 1 = 10
    
  • We can write a recursive definition to the problem
  • S(x) = x + S(x - 1)
    S(1) = 1
    
  • Can convert the solution into a method named sum
  • public class RecursiveSums {
        static int sum(int x) {
            int result;
            if (x == 1)
                result = 1;
            else
                result = x + sum(x - 1);
            return result;
        }
    
        public static void main(String[] args) {
            int sum4 = sum(4);
            System.out.println(sum4);
        }
    }
  • Note how our definition is embodied in the sum method

13.2.3: Tracing the Execution

  • How does the method actually work?
  • Can trace the sum(4) called from main
  • main() calls sum(4)
        sum(4) calls sum(3)
            sum(3) calls sum(2)
                sum(2) calls sum(1)
                    sum(1) returns 1
                sum(2) returns 3
            sum(3) returns 6
        sum(4) returns 10
    main() assigns return value of 10 to sum4
    
  • Note that the first half makes successive method calls
    • Until the base case is reached
  • Second half returns the values of the recursive case

13.2.4: Recursion vs. Iteration

  • All recursive algorithms or methods can be rewritten without recursion
  • Methods rewritten without recursion usually have loops, so they are called iterative methods
  • For example, we could write an iterative version of sum:
  • static int sum(int x) {
        int result = 0;
        for (int i = 1; i <= x; i++)
            result += i;
        return result;
    }
    

Iteration

  • Uses repetition structures (for, while or do-while)
  • Repetition through explicit use of repetition structure
  • Terminates when loop-continuation condition fails
  • Controls repetition by using a counter variable

Recursion

  • Uses selection structures (if, if-else or switch)
  • Repetition through repeated method calls
  • Terminates when base case is satisfied
  • Controls repetition by dividing problems into simpler ones

Choosing Recursion or Iteration

  • Recursion has more overhead than iteration
    • More memory used
    • More processor steps taken
  • Iterative methods generally run faster and use less memory space
  • Recursion often shows the algorithm more clearly
    • Can be implemented with only a few lines of code

    When should you use recursion?

  • When efficiency is not important and it makes the code easier to understand

13.2.5 Summary

  • Recursive methods implement recursive algorithms
  • Methods call themselves either directly or indirectly through another method
  • General form of recursive methods:
  • returnValue recursiveMethod(arguments) {
        If (stopping condition) { // base case
            /* do whatever at the end */;
        } else {
            //execute recursive step
            recursiveMethod(arguments);
        }
    }
    
  • All recursive methods can be rewritten without recursion
    • Use iterative (looping) statements rather than recursive method calls
  • Use recursion when efficiency is not important and it makes the code easier to understand
  • Otherwise, use iteration

Exercise 13.2

Use the next 5 minutes to complete the following. We will discuss the question after the time has elapsed.

  1. Write a program to solve i * j recursively. Use the definition we defined in the prior exercise. Submit your code with the exercises for this lesson.

13.3: Lecture Finale

Objectives

At the end of the lesson the student will be able to:

  • Discuss the final preparation for the project presentation
  • Advise the instructor on how to improve future courses

13.3.1: What We Have Learned

During the course, we have learned how to:

  1. Compile source code into Java bytecode
  2. Run Java programs
  3. Declare classes and work with data types
  4. Use arithmetic expressions
  5. Declare and use variables to store data
  6. Display program output, both to the console and to a dialog
  7. Collect data from users using dialogs
  8. Use conditional statements to make our applications appear intelligent
  9. Use loops to repeat code
  10. Validate user input to verify our programs receive the proper type of data
  11. Write methods to group related code
  12. Use a professional coding style
  13. Create classes and objects
  14. Use inheritance to extend our classes and to enhance their functionality
  15. Design programs using classes and objects
  16. Use and throw exceptions
  17. Use arrays to group our data
  18. Perform common programming tasks on arrays
  19. Construct and process string data
  20. Use files and streams for program input and output
  21. Create and use interfaces
  22. Code graphical user interfaces (GUIs)
  23. Create Applets for use on the World-Wide Web
  24. Start thinking and programming recursively
  • With this knowledge, you can create programs of moderate complexity
  • Also, you have a solid foundation for more advanced programming
  • Your sampler project will allow you to demonstrate what you have learned

13.3.2: End of Course Survey

  • Please take a few minutes to answer this short survey
  • This will help the instructor to improve future courses
  • Survey respondent answers are anonymous
  • The link to WebCT is here
  • You may want to rate the textbook at your favorite book seller, such as:

13.3.3: About the Project Presentation

Before the Presentation

  • Submit the following to WebCT before the presentation:
    1. README.txt file
    2. All source code files
    3. Any data files required
    4. Sampler Report
  • Bring a written report on paper to give to the instructor
  • If you submit a zip file, the file must extract into a directory that the instructor chooses. Please do NOT use absolute (full) paths.

During the Presentation

The presentation consists of the following information:

  • A brief introduction describing the purpose of your application
  • A demonstration of your sampler project
  • A summary list of the functional specifications and a brief description of how you met these requirements in your project
  • A list of any extra-credit features
    • Point out the extras so we can all appreciate them
  • Try to keep the presentation to 10 minutes or less

After the Presentation

  • Feel free to leave (or stay) after your presentation
  • You can present to the instructor alone after the other presentations are through

Part 1 Wrap Up

Part 2: What We Will Cover

Continuations

Questions on Completed Assignment?

Questions from last class?

13.4: Final Exam Preparation

Objectives

At the end of the lesson the student will be able to:

  • Discuss how to prepare for the final exam
  • Describe how to take the final exam

13.4.1: About the Final Exam

Important Exam Information

Date and Time: 12/15/03 @ 7:00 A.M. to 9:50 A.M.
Location: Room 516 (regular classroom)

  • You must attend the exam or you will receive a score of zero (0)
    • Except by prior arrangement with the instructor
  • I am using WebCT to administer the test
  • The exam is designed to take about 1.5 hours to complete
  • However, you will have the full scheduled time to complete the exam
    • You may have less time if you are late to the exam
  • The exam is closed books and closed notes
    • However, you may have one 3" x 5" card of notes for the exam
  • You may use your computer for taking the exam in WebCT
  • You may use the computer to compile or run programs
  • You may NOT use the computer to use the Internet
  • You may NOT communicate with your neighbor during the exam

13.4.2: Recommended Preparation

  1. Work through the Practice Final Exam questions
    • Working the problems in groups is encouraged
    • Get explanations for anything you do not understand
  2. Review your notes and prepare your 3" x 5" card
  3. Review the questions from the midterm exams
  4. Review your homework assignments and solutions
  5. Get plenty of rest before the exam

13.4.3: Exam Taking Tips

  • Save after every answer -- you can always choose another answer
  • If you get stuck on a question, make your best guess and return later
  • If you are equally uncertain between two choices, go with first impression
  • You do not need to comment code for tests and exams
    • Unless specifically instructed to in the exam question
  • Use the full time available
  • More quiz tips: Basic Rules For Taking a Multiple-Choice Test

13.4.4: Questions and Answers

  • Any questions?

13.5: Sampler Presentation

Objectives

At the end of the lesson the student will be able to:

  • Present their sampler assignment

13.5.1: Sampler Presentation

Before the Presentation

  • Submit the following to WebCT before the presentation:
    1. README.txt file
    2. All source code (i.e. .java files)
    3. Any other source code needed to make your program function.
  • Bring a written report on paper to give to the instructor
  • If you submit a zip file, the file must extract into a directory that the instructor chooses. Please do NOT use absolute (full) paths.

During the Presentation

Present the following information:

  • A brief introduction describing the purpose of your application
  • A demonstration of your sampler project
  • A summary list of the functional specifications and a brief description of how you met these requirements in your project
  • A list of any extra-credit features
    • Point out the extras so we can all appreciate them
  • Try to keep the presentation to 10 minutes or less

After the Presentation

  • Feel free to leave (or stay) after your presentation
  • You can present to the instructor alone after the other presentations are through

Home | WebCT | Announcements | Schedule | Expectations | Syllabus
Help | FAQ's | HowTo's | Links

Last Updated: December 08 2003 @11:11:58