next up previous
Next: Iteration Up: Assignment 6: Iteration Previous: Assignment 6: Iteration

Recursion

1.
Create a new project called Sum.prj, and type in the following two methods.

  public static int methOne (int m, int n) {
    if (m == n) {
      return n;
    } else {
      return m + methOne (m+1, n);
    }
  }

  public static int methTwo (int m, int n) {
    if (m == n) {
      return n;
    } else {
      return n * methTwo (m, n-1);
    }
  }
2.
Add a few lines to main to test these methods. Invoke them a couple of times, with a few different values, and see what you get. By some combination of testing and examination of the code, figure out what these methods do, and give them more meaningful names. Add comments that describe their function abstractly.

3.
Add a println statement to the beginning of both methods so that they print their arguments each time they are invoked. This is a useful technique for debugging recursive programs, since it effectively ``follows the stack'' for you.

4.
Write a recursive method called power that takes a double x and an integer n and that returns xn. Hint: a recursive definition of this operation is power (x, n) = x * power (x, n-1). Also, remember that anything raised to the zeroeth power is 1.



Allen B. Downey
1999-10-12