简体   繁体   中英

How does recursion work here?

Recursion is a new practice for me and I am trying to get better at it and understand how the methods return. I have the following program but am unfailiar with how to use the this keyword. Can you please review the code and walk me through the program showing the values held by the variables as the methods execute?

I have tried numerous things to determine how the value answer in the compute method holds 14 after execution can anyone walk me through the first few recursive calls so I can try and figure out the rest?

public class Recurs1 {
    public static void main (String [] arg) {
        Recurs1 r = new Recurs1();
        r.compute();

    }
    public void compute() {
        int [] stuff = {1, 2, 3, 4};
        int answer = this.go(stuff, 0);
        System.out.println("The answer is " + answer);

    }
    private int go(int[] numbers, int spot) {
        if (numbers.length == spot) return spot;
        int value = this.go(numbers, spot + 1 ); 
        return value + numbers[spot];
    }

}

Ok so a few things I notice here:

The purpose of go() seems to be calculating the sum of the numbers in the array. If this is the case, your method should look like this:

private int go(int[] numbers, int spot) {
        if (numbers.length - 1 == spot) return numbers[spot];
        int value = this.go(numbers, spot + 1 ); 
        return value + numbers[spot];
    }

This is because numbers.length in this case will return 4, but the last element in this array is at index 3 (arrays are 0-indexed).

This way, when the function is called with the second parameter set to 3, it will return the value of the last element in the array and then the code will "bubble up" (as I like to call it) and calculate the sum of the elements by subsequently returning the current summed value + the value of the current call.

As for your problem with the this keyword, it's actually very simple. this always refers to the current class instance your code is in. In this case, you create a Recurs1 instance called r in your main function so whenever you call a method on that particular object, the this keyword used in those methods will refer to r . If you created multiple Recurs1 objects (each with potential different internal states) in your program, their respective this references would always point to themselves allowing you to access their member variables and methods.

Hope that helps and good luck, recursion is usually what most people have trouble getting their heads around at first but once you get used to it it's pretty cool!

OK so this is not an answer to your question per se, more like a lesson in recursion.

Keep in mind I have never tried to to do this with a java class.

Recursion means a function that calls itself repeatedly until a answer has been reached, or your function detects you are running out of stack space.

You first step into the function determines if you will call yourself.

When you call yourself you will push a new copy of the data onto the stack and begin executing. I think in the case of java you will allocate a new object into the heap ( don't quote me on this ) and each invocation will have a new set of variables that get populated with new values.

As you recurse deeper and deeper you simply allocate new copies of the object until you find the answer or run out of memory.

If you find the answer you then return the result to the previous level in the stack of objects eg:

int foo(int i ){
  if(some condition){ 
   return foo(i);
  } else
   return i  
}

as You can see if the condition tests true the foo() keeps getting called. Now at each call, the variables of foo() are saved for as many levels deep as you go. If the condition tests false then each instance of foo() returns to the previous until you are at the original invocation of foo() which then returns to the caller of foo().

Clear as Mud?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM