{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Lecture 10-Recursion

# Lecture 10-Recursion - Read pp 403-408 but SKIP sect 15.1.2...

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

1 1 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 ProgramLive CD, page 15-3, has 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 later. Recursion is an important programming tool. Purely functional languages have no loops —only recursion. CS1110 30 September. Recursion Prelim I 7:30–9:00PM Thursday, 7 Oct /** = the number of ‘e’s in s */ public String noe(String s) { if (s.length() == 0) { return 0; } // { s has at least one char } } 2 Called the base case Called the recursive case Express the answer with the same terminology as the specification, but on a smaller scale: number of ‘e’s in s = (if s[0] = ‘e’ then 1 else 0) + number of ‘e’s in s[1..] return (s[0] = ‘e’ ? 1 : 0) + noe(s.substring(1)); Notation: s[i] shorthand for s.charAt[i]. s[i..] shorthand for s.substring(i). s 0 1 s.length() 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 discussed the first issue earlier. 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. We do this in the next lecture. DON’T try to understand a recursive method by executing its recursive calls! Use execution only to understand how it works.

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}