Search code examples
javarecursioncompositiondecomposition

How to draw a decomposition and composition for a method?


Consider the following code fragment

public int fun(int a, int b) {
    if (b == 1)
        return a;
    else
        return a + fun(a, b - 1);
}

a. Draw the decomposition & composition of fun(2,4)

b. What would be the value of fun(2,0)?Discuss and show a screenshot that proves your answer.

here is the screenshot


Solution

  • a. Draw the decomposition & composition of fun(2,4)

    Your question sounds like a homework task and I don't want to do the work for you.

    That said, I can draw the decomposition/composition diagram for another example to give you an idea.

    Here's a diagram for fun(0,3):

    Decomposition/composition diagram

    where black arrows indicate the decomposition and blue arrows the composition of fun(0,3).

    The decomposition procedure (black):

    1. Draw fun(0, 3)

    2. By examining your code, you can see that in order to compute fun(0, 3), you first have to compute fun(0, 2), so you draw fun(0, 2)

    3. In order to compute fun(0, 2), you first have to compute fun(0, 1), so you draw fun(0, 1)

    The composition procedure (blue):

    1. fun(0, 1) returns a, or in your case 0

    2. You can now compute fun(0, 2) = a + fun(0, 1) = 0 + 0 = 0

    3. And finally, you can compute fun(0, 3) = a + fun(0, 2) = 0 + 0 = 0


    b. What would be the value of fun(2,0)?Discuss and show a screenshot that proves your answer.

    As you've seen, that particular case produces a StackOverflow error. If you tried drawing a decomposition/composition diagram for that case, you'd end up with a single, endless branch.