Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Recursion - What is it? - When is it used? - Examples

Similar presentations


Presentation on theme: "Introduction to Recursion - What is it? - When is it used? - Examples"— Presentation transcript:

1 Introduction to Recursion - What is it? - When is it used? - Examples

2 A Recursive Method – A method that calls itself.
Very important concept for: Fast sort algorithms Binary tree traversals (Computer Science AB) Fractal Generation

3 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!!

4 Handout and Examples 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 + ",");

5 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) ____________

6 Handout and Examples 1. What is returned by the call compute(1, 5)?
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)

7 Programming Example Write a recursive method that computes the number of cubes in a pyramid of cubes that is n cubes high.


Download ppt "Introduction to Recursion - What is it? - When is it used? - Examples"

Similar presentations


Ads by Google