next up previous
Next: Moiré patterns Up: Assignment 6: Iteration Previous: Assignment 6: Iteration

Recursion and iteration

1.
In class, we have worked with two similar recursive methods, sum and product. Create a new project called Sum, and type in both methods.

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

  public static int product (int m, int n) {
    if (m == n) {
      return n;
    } else {
      return n * product (m, n-1);
    }
  }
2.
Add a few lines to main to test these methods and make sure they do what they are supposed to do.

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.
Read Chapter 6, and type in at least one of the loops. Add a print statement to the loop to print the value of the loop variable during each iteration. Notice the connection between a loop iteration and a recursion.

5.
Write an iterative method named itSum that does the same thing as sum except that it should use a while statement to iterate instead of recursing.

6.
Write an iterative version of product called itProduct.



Allen B. Downey
1999-03-08