UIL CS: Recursion & Loops

This is part of the UIL CS study series. See also:

Main topic list: https://www.uiltexas.org/files/academics/UILCS-JavaTopicList2526.pdf


8. Recursion Tracing (example)

static int f(int n) {
    if (n <= 1) return 1;
    return n * f(n - 2);
}

Trace f(7)f(7):

f(7)=7f(5)f(5)=5f(3)f(3)=3f(1)f(1)=1\begin{aligned} f(7) &= 7 \cdot f(5) \\ f(5) &= 5 \cdot f(3) \\ f(3) &= 3 \cdot f(1) \\ f(1) &= 1 \end{aligned}

Back-substitute:

f(3)=31=3f(5)=53=15f(7)=715=105\begin{aligned} f(3) &= 3 \cdot 1 = 3 \\ f(5) &= 5 \cdot 3 = 15 \\ f(7) &= 7 \cdot 15 = 105 \end{aligned}

9. Tracing a Nested Loop (example)

int count = 0;
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= i; j++) {
        count += i + j;
    }
}
System.out.println(count);

Trace:

  • i=1i=1: j=1j=1 \rightarrow add (1+1)=2(1+1)=2 \rightarrow count=2
  • i=2i=2: j=1j=1 \rightarrow add 33 \rightarrow count=5 j=2j=2 \rightarrow add 44 \rightarrow count=9
  • i=3i=3: j=1j=1 \rightarrow add 44 \rightarrow count=13 j=2j=2 \rightarrow add 55 \rightarrow count=18 j=3j=3 \rightarrow add 66 \rightarrow count=24

Output: 2424


10. Math.random() and Random

Math.random()

Returns double in [0.0,1.0)[0.0, 1.0)

Common patterns:

int x = (int)(Math.random() * 10);          // 0..9
int y = (int)(Math.random() * 6) + 1;       // 1..6
int z = (int)(Math.random() * (b - a + 1)) + a; // a..b

Random class

Random r = new Random(); // or new Random(seed)
int a = r.nextInt(10);       // 0..9
int b = r.nextInt(6) + 1;    // 1..6
double d = r.nextDouble();   // [0.0, 1.0)
boolean ok = r.nextBoolean();

12. Pass-By-Value in Java

Java always passes primitive values by value. For objects, reference copies are passed. Assigning to a parameter doesn't change the original reference.


13. Exceptions/Errors

  • Recognize common runtime errors (e.g., NullPointerException, NumberFormatException, array index errors).
  • Checked exceptions require try/catch or throws declaration.
  • The compiler only checks syntax and type safety; actual variable values exist at run time.
  • Local, uninitialized variables will throw a compiler (syntax) error if you attempt to use them. On the other hand, class-level variables (both instance fields and static) are provided a default value by the compiler, and thus do not throw errors.
    • Numeric default values (e.g., short, int, long, float, double): 00, 0.00.0, or 0.0f0.0f
    • Boolean default value: false
    • Char default value: '\u0000'
    • Reference type default value (e.g., String): null

15. Arrays & Strings

Arrays: traversal, indexing, mutation. Multi-dimensional arrays.

Strings: substring, charAt, concatenation. String to char array: "abc".toCharArray().