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 :
Back-substitute:
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:
- : add count=2
- : add count=5 add count=9
- : add count=13 add count=18 add count=24
Output:
10. Math.random() and Random
Math.random()
Returns double in
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/catchorthrowsdeclaration. - 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): , , or
- 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().