This preview shows pages 1–7. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Recursion Mathematical Background EECS 2332 NonRecursive Programming Nonrecursive 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) = …4 How Does Recursion Work? In writing a recursive method, we solve a larger problem by reducing the problem to smaller and smaller subproblems. We keep doing this until we reach a subproblem 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 problem5 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 x6 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 (modiFed arguments); … // possibly do something here } } When we make the recursive call, we typically use arguments that bring us closer to the base case....
View
Full
Document
This note was uploaded on 04/07/2008 for the course EECS 233 taught by Professor Rabinovich during the Spring '08 term at Case Western.
 Spring '08
 Rabinovich
 Recursion

Click to edit the document details