Consider the following Java code that uses recursion. What will be printed when countdown(3) is called?
public class Test { public static void countdown(int n) { if (n == 0) { System.out.println("Done"); return; } System.out.println(n); countdown(n - 1); } public static void main(String[] args) { countdown(3); } }
Think about how the function prints before the recursive call and what happens when n reaches zero.
The method prints the current number n before calling itself with n-1. When n reaches zero, it prints "Done" and returns. So the output is numbers 3, 2, 1 each on their own line, then "Done".
Given the following Java code, what is the value of result after main finishes?
public class Test { public static int addOne(int x) { return x + 1; } public static int doubleIt(int x) { return x * 2; } public static void main(String[] args) { int result = doubleIt(addOne(3)); System.out.println(result); } }
Remember the order of method calls and how the call stack works.
The method addOne(3) returns 4. Then doubleIt(4) returns 8. So result is 8.
Examine the following Java code with two mutually recursive methods. What is the output when foo(2) is called?
public class Test { public static void foo(int n) { System.out.println("foo " + n); if (n == 0) { System.out.println("foo done"); return; } bar(n - 1); } public static void bar(int n) { if (n == 0) { System.out.println("bar done"); return; } System.out.println("bar " + n); foo(n / 2); } public static void main(String[] args) { foo(2); } }
Trace the calls carefully, noting how n / 2 behaves with integer division.
Calling foo(2) prints "foo 2" then calls bar(1). bar(1) prints "bar 1" then calls foo(0). foo(0) prints "foo 0" then "foo done" and returns. Then bar(1) returns, then foo(2) returns.
Consider this Java method that calls itself without a base case. What error will occur when infiniteRecursion() is called?
public class Test { public static void infiniteRecursion() { infiniteRecursion(); } public static void main(String[] args) { infiniteRecursion(); } }
Think about what happens when a method keeps calling itself without stopping.
The method calls itself endlessly without a base case, causing the call stack to grow until it exceeds its limit, resulting in a StackOverflowError.
Given the following factorial method, how many stack frames are created when factorial(5) is called?
public class Test { public static int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } public static void main(String[] args) { int result = factorial(5); System.out.println(result); } }
Count the initial call plus each recursive call until the base case.
Calling factorial(5) creates stack frames for n=5,4,3,2,1 (base case). That is 6 frames total.
