javarecursion

Trace a recursive method


I am finding it very confusing to understand the concept of recursion. I am trying to trace a recursive function. Can someone please help me with that?

    public static int h(int n){
        if (n == 0)
            return 0;
        else
            return h(n-1)+1;
    }

When I write

int a = h(5);
System.out.println(a)

I dont understand how the result produced is actually coming?


Solution

  • First of all, if you have difficulty in understanding the concept of recursion, I think the following links will help you:

    You may use the debugging facility on your IDE to see how it is working. You may Google for instructions on how to set beakpoints and use the debugger to step through the program.

    About the method h, It will return what you given as input(if it is a positive number or 0). Also large numbers & negative numbers will cause a StackOverflowError. To know the working you may use a print statement inside your method.

    public static int h(int n) {
        System.out.println("h(" + n + ")");
        if (n == 0) {
            System.out.println("value: 0");
            return 0;
        } else {
            System.out.println("going down");
            int temp = h(n - 1) + 1;
            System.out.println("h(" + n + ") --> " + temp);
            return temp;
        }
    }
    

    will output:

    h(5)
    going down
    h(4)
    going down
    h(3)
    going down
    h(2)
    going down
    h(1)
    going down
    h(0)
    value: 0
    h(1) --> 1
    h(2) --> 2
    h(3) --> 3
    h(4) --> 4
    h(5) --> 5
    

    The above output can be edited to show the working:

    h(5)
    |    going down
    |----h(4)
    |    |   going down
    |    |---h(3)
    |    |   |   going down
    |    |   |---h(2)
    |    |   |   |  going down
    |    |   |   |--h(1)
    |    |   |   |  |    going down
    |    |   |   |  |----h(0)
    |    |   |   |  |    |    value: 0 --> return 0;
    |    |   |   |  |    h(1) --> 1 --> h(0) + 1 = 0 + 1 = 1
    |    |   |   |  h(2) --> 2          h(1) + 1 = 1 + 1 = 2
    |    |   |   h(3) --> 3             h(2) + 2 = 1 + 1 = 3
    |    |   h(4) --> 4                 h(3) + 3 = 1 + 1 = 4
    |    h(5) --> 5                     h(4) + 4 = 1 + 1 = 5
    

    The following is the non-recursive version of the method h.

    public static int nonh(int n) {
        int result = 0;
        for (int i = n; i > 0; i--) {
            result += 1;
        }
    
        return result;
    }
    

    Hope that helps :)