09-07feb20recursion - CS100J February 20 Recursion Read:...

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

View Full Document Right Arrow Icon
1 CS100J February 20 Recursion Recursion : If you get the point, stop; otherwise, see Recursion. Infinite recursion : See Infinite recursion. Read: pp. 403-408 but SKIP sect. 15.1.2 Look in ProgramLive CD, page 15-3, for some interesting recursive methods. Download presented algorithms from the website Recursive definition : A definition that is defined in terms of itself. Recursive method : a method that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops), which we cover next. Recursion is an important programming tool. Functional languages have no loops —only recursion. 2 Turn recursive definition into recursive function Factorial : !0 = 1 base case !n = n * !(n-1) for n > 0 recursive case Thus, !3 = 3 * !2 = 3 * 2 * !1 = 3 * 2 * 1 * !0 = 3 * 2 * 1 * 1 (= 6) // = !n (for n 0) public static int fact( int n) { if (n == 0) { return 1; base case } // {n > 0} an assertion return n * fact(n-1); recursive case } (a recursive call) note the precise specification 3 Two issues in coming to grips with recursion 1. How are recursive calls executed? 2. How do we understand a recursive method and how do we create one? We discuss the first issue later. Suffice it to say that if you execute a call on a recursive method, carefully using our model of execution, you will see that it works. Briefly, a new frame is created for each recursive call. DON’T try to understand a recursive method by executing its recursive calls! Use execution only to understand how it works.
Background image of page 1

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

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 2

09-07feb20recursion - CS100J February 20 Recursion Read:...

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

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