University of Washington, AP/CS A

Lab 2: Recursion

Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

Today's lab

Goals for this lab:

Exercise : Recursive Tracing (12.1)

Consider the following method.

public int mystery1(int x, int y) {
    if (x < y) {
        return x;
    } else {
        return mystery1(x - y, y);
    }
}

Fill in the boxes with the value returned by each of the method calls.

mystery1(6, 13)
6
mystery1(14, 10)
4
mystery1(37, 10)
7
mystery1(8, 2)
0
mystery1(50, 7)
1

Exercise : Recursive Tracing (12.1)

Consider the following method.

public void mystery2(int n) {
    if (n <= 1) {
        System.out.print(n);
    } else {
        mystery2(n / 2);
        System.out.print(", " + n);
    }
}

Fill in the boxes with the output produced by each of the method calls.

mystery2(1);
1
mystery2(4);
1, 2, 4
mystery2(16);
1, 2, 4, 8, 16
mystery2(30);
1, 3, 7, 15, 30
mystery2(100);
1, 3, 6, 12, 25, 50, 100

Exercise : Recursive Tracing (12.1)

Consider the following method.

public int mystery3(int n) {
    if (n < 0) {
        return mystery3(-n);
    } else if (n < 10) {
        return n;
    } else {
        return n % 10 + mystery3(n / 10);
    }
}

Fill in the boxes with the value returned by each of the method calls.

mystery3(8)
8
mystery3(74)
11
mystery3(-52)
7
mystery3(3052)
10
mystery3(82534)
22

Exercise : Recursive Tracing (12.1)

Consider the following method.

public void mystery4(int x, int y) {
    if (y == 1) {
        System.out.print(x);
    } else {
        System.out.print(x * y + ", ");
        mystery4(x, y - 1);
        System.out.print(", " + x * y);
    }
}

Fill in the boxes with the output produced by each of the method calls.

mystery4(4, 1);
4
mystery4(4, 2);
8, 4, 8
mystery4(8, 2);
16, 8, 16
mystery4(4, 3);
12, 8, 4, 8, 12
mystery4(3, 4);
12, 9, 6, 3, 6, 9, 12

Exercise : Recursive Tracing (12.1)

Consider the following method.

  public void mystery5(int n) {
      if (n <= 0) {
          System.out.print("*");
      } else if (n % 2 == 0) {
          System.out.print("(");
          mystery5(n - 1);
          System.out.print(")");
      } else {
          System.out.print("[");
          mystery5(n - 1);
          System.out.print("]");
      }
  }

Fill in the boxes with the output produced by each of the method calls.

mystery5(0);
*
mystery5(1);
[*]
mystery5(2);
([*])
mystery5(4);
([([*])])
mystery5(5);
[([([*])])]