{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Lecture3

# Lecture3 - Recursion Mathematical Background EECS 233...

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

Recursion Mathematical Background EECS 233

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

View Full Document
-2- Non-Recursive Programming Non-recursive programming is more familiar. Calculate Σ i , i =1,..., n using a “for” loop int sum(int n) { int i, sum; sum = 0; for (i = 1; i <= n; i++) sum += i; return sum; }
-3- What is Recursion? A recursive method is a method that invokes itself. int sum(int n) { if (n <= 0) return 0; int sum_result = n + sum(n – 1); return sum_result; } sum(6) = 6 + sum(5) = 6 + 5 + sum(4) = …

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

View Full Document
-4- How Does Recursion Work? In writing a recursive method, we solve a larger problem by reducing the problem to smaller and smaller sub-problems. We keep doing this until we reach a sub-problem that is trivial to solve directly. This is known as the base case . int sum(int n) { if (n <= 0) // base case return 0; int sum = n + sum(n – 1); // recursive call return sum; } The base case stops the recursion. If the base case hasn't been reached, we: make one or more recursive calls to solve smaller problems use the solutions to the smaller problems to solve the original problem
-5- Tracking Recursive Calls Assume the main() method calls x = sum(3). What happens? int sum(int n) { if (n <= 0) // base case return 0; int sum_res = n + sum(n – 1); // recursive call return sum_res; } main() { … x = sum(3); … } args x n=3 sum s return addr in “main” sum s return addr in “sum” n=2 sum s return addr in “sum” n=1 sum s return addr in “sum” n=0 main() calls sum(3) sum(3) calls sum(2) sum(2) calls sum(1) sum(1) calls sum(0) sum(0) returns 0 sum(1) returns 1 + 0, or 1 sum(2) returns 2 + 1, or 3 sum(3) returns 3 + 3, or 6 main() assigns 6 to x

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

View Full Document
-6- How To Design A Recursive Method? Basic structure: recursiveMethod (arguments) { If (stopping condition) // base case … // handle the base case else { // recursive case … // possibly do something here recursiveMethod (modified arguments); … // possibly do something here } } When we make the recursive call, we typically use arguments that bring us closer to the base case.
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}