Lecture 24 (Sherriff) - Methods and Recursion

Lecture Date: Monday, March 16

Now that we’ve looked at how methods work, we’re going to look at a particular category of methods: methods that call themselves within their own code. These are called recursive methods.

Recursion

Colbert

Something that is recursive is something that is defined in terms of itself.

Try Googling for Recursion. See anything amusing?

Lots of things can be recursive: pictures, acronyms, parts of nature…

When we look at a recursive algorithm, we’re looking for three particular things:

  1. Recursive Case: under some condition it invokes itself.

  2. Base Case: under some condition it does not invoke itself.

  3. Progress: each time it invokes itself it gets closer to the base case.

We’ll look at a few recursive algorithms today, including power, fibonacci, and string reverse.

Recursion.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Recursion {

  public static void main(String[] args) {
      System.out.println(power(3,5));
      System.out.println(reverse("Bubba"));

  }
  
  public static int power(int x, int y) {
      if(y == 1) {
          return x;
      }
      return x * power(x, (y-1));
      
  }
  
  public static String reverse(String str) {
      if(str.length() <= 1) {
          return str;
      }
      return str.charAt(str.length()-1) + reverse(str.substring(0, str.length()-1));
      
  }
  
  public static String reverseIt(String str) {
      String temp = "";
      for(int i = str.length()-1; i >= 0; i--) {
          temp += str.charAt(i);
          
      }
      return temp;
      
  }

}

Recursion.java

Fib GUI Example