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

Iteration

1.
Read Chapter 6, and type the following loop:

  public static void sequence (int n) {
    while (n != 1) {
      System.out.println (n);
      if (n%2 == 0) {           // n is even
        n = n / 2;
      } else {                  // n is odd
        n = n*3 + 1;
      }
    }
  }

2.
Add some code in main that invokes this method and test it with a variety of starting value. Notice that the first thing it does during each iteration is print the value of the loop variable. This is a useful technique for debugging iterative programs.

3.
Write an iterative version of the power method in the previous section.

4.
Write an iterative version of factorial.



Allen B. Downey
1999-10-12