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:

  1. A.

    ‐2‐25‐3‐135

  2. B.

    ‐2‐25‐1‐3‐135

  3. C.

    ‐1‐145‐2‐245

  4. 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.

  1. Base case: For any N <= 0, F(N) = "-".

  2. Compute F(1):

    F(1) = F(-2) + "1" + F(-1) + "1" = "-" + "1" + "-" + "1" = "-1-1".

  3. Compute F(2):

    F(2) = F(-1) + "2" + F(0) + "2" = "-" + "2" + "-" + "2" = "-2-2".

  4. Compute F(3):

    F(3) = F(0) + "3" + F(1) + "3" = "-" + "3" + "-1-1" + "3" = "-3-1-13".

  5. 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".

Explore the full course: Nta Ugc Net Paper 2

Loading lesson…