Consider the following recursive function F() in Java that takes an integer…
2021
Consider the following recursive function F() in Java that takes an integer value and returns a string value:
public static String F( int N) {
if ( N <= 0) return "‐";
return F(N ‐ 3) + N + F(N ‐ 2) + N;
}
The value of F(5) is:
- A.
‐2‐25‐3‐135
- B.
‐2‐25‐1‐3‐135
- C.
‐1‐145‐2‐245
- D.
‐2‐25‐3‐1‐135
Attempted by 108 students.
Show answer & explanation
Correct answer: D
Key idea: use the base case F(N) = "-" for N <= 0 and expand the recursion step-by-step.
Base case: For any N <= 0, F(N) = "-".
Compute F(1):
F(1) = F(-2) + "1" + F(-1) + "1" = "-" + "1" + "-" + "1" = "-1-1".
Compute F(2):
F(2) = F(-1) + "2" + F(0) + "2" = "-" + "2" + "-" + "2" = "-2-2".
Compute F(3):
F(3) = F(0) + "3" + F(1) + "3" = "-" + "3" + "-1-1" + "3" = "-3-1-13".
Compute F(5) using F(2) and F(3):
F(5) = F(2) + "5" + F(3) + "5" = "-2-2" + "5" + "-3-1-13" + "5" = "-2-25-3-1-135".
Therefore the value of F(5) is "-2-25-3-1-135".