Introduction to Recursion What is it When is







- Slides: 7
Introduction to Recursion - What is it? - When is it used? - Examples 1 AP Computer Science A – Healdsburg High School
A Recursive Method – A method that calls itself. Very important concept for: Fast sort algorithms Binary tree traversals (Computer Science AB) Fractal Generation 2 AP Computer Science A – Healdsburg High School
The parts of a Recursive Method 1. The Recursive Call: generally, the method calls itself to perform a simpler version of the original problem. 2. The Stop Condition: each recursive method needs a condition which does not call itself. This is where the “winding up” occurs. NO STOP CONDITION LEADS TO INFINITE RECURSION!! 3 AP Computer Science A – Healdsburg High School
Handout and Examples 1. Please enter your value of n here when it is your turn _______ public void mystery (int n) { if (n <= 0) System. out. print(0); else if (n%2 == 0) { mystery(n-1); System. out. print(", " + n*n); } else { System. out. print(n*n + ", "); mystery(n-1); } 4 } AP Computer Science A – Healdsburg High School
Handout and Examples 2. Consider the following recursive method: public int foo(int x, int y) { if (x < y) return x; else return foo(x-y, y); } For each function call below, indicate what value is returned: Method call Value Returned foo(6, 13) ______ foo(14, 10) ______ foo(37, 10) ______ foo(8, 2) ______ foo(50, 7) ______ 5 AP Computer Science A – Healdsburg High School
Handout and Examples public static int compute(int x, int y) { if(x == y) return x; else return (compute(x+1, y-1)); } 1. What is returned by the call compute(1, 5)? 2. Which of the following calls leads to infinite recursion? I. compute(2, 8) II. compute(8, 2) III. compute(2, 5) 6 AP Computer Science A – Healdsburg High School
Programming Example Write a recursive method that computes the number of cubes in a pyramid of cubes that is n cubes high. 7 AP Computer Science A – Healdsburg High School