1 / 9

Object-oriented programming CSI32

Object-oriented programming CSI32. Dr. Sharon Persinger October 30, 2013. Recursion. Recursion is a type of repetition used in mathematics and computing to create objects and to define functions.

vui
Download Presentation

Object-oriented programming CSI32

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object-oriented programmingCSI32 Dr. Sharon Persinger October 30, 2013

  2. Recursion • Recursion is a type of repetition used in mathematics and computing to create objects and to define functions. • The key to recursion is to see that some objects or functions have smaller instances of the same object or function inside them.

  3. Functional recursion • Functional recursion allows you to define a function in terms of itself. (What?) • A recursive definition for a function F includes a call of the function F in the function definition for F.

  4. Example: Factorial function F • F(n)= n(n-1)(n-2)…3⋅2⋅1, for integer n ≥0 • F(0) = 1 • Can you see a factorial on the right hand side of the definition?

  5. Example: Factorial function F • Base case: F(0) = 1; F(1) = 1 • Recursive case: for n ≥2, F(n) = n ⋅F(n-1) • Trace the evaluation of F(4). • In Python, an activation record keeps track of information relevant to a function call – parameter values, interruptions. • Write a recursive definition in Python for the factorial function

  6. Programming Assignment • Write a recursive definition for the factorial function. Now!

  7. Recursive GCD function using Euclid’s algorithm • Remember Euclid’s Algorithm from CSI30? • Key idea: GCD(A, B) = GCD(B, A mod B) • Do example GCD(300, 45) • When do you know the GCD? • What is the base case? • What does the recursive call look like?

  8. Recursive GCD function • Write a recursive definition for GCD using Euclid’s algorithm – Now!

  9. Recursive function definition for G • There must be one or more base cases that can be evaluated without calling G • There must be one or more cases where G is evaluated by calling G on a simpler or smaller input – recursive call. • Every recursive call must end in a base case.

More Related