Note that there are some explanatory texts on larger screens.

plurals
  1. POReturns from Recursive methods
    primarykey
    data
    text
    <p>I am trying to practice understanding recursion but the following program has me stumped. How is the answer being returned as 14? Can someone show me how this is calculating? I tried to put in afew print statments to help me identify what is going on but I do not see how spot is decremented after it goes up to 4. I have the program and output to console below, please help.</p> <p>from console: </p> <pre><code>The spot 1 is 0 The spot 1 is 1 The spot 1 is 2 The spot 1 is 3 The spot 1 is 4 when spot = length. the spot is 4 The value is 4 spot after return 3 the spot 2 is 3 The value is 8 spot after return 2 the spot 2 is 2 The value is 11 spot after return 1 the spot 2 is 1 The value is 13 spot after return 0 the spot 2 is 0 The answer is 14 </code></pre> <p>Code:</p> <pre><code>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 = go(stuff, 0); System.out.println("The answer is " + answer); } private int go(int[] numbers, int spot) { System.out.println("The spot 1 is " + spot); //System.out.println("0 is " + numbers[0] + " 1 is " + numbers[1] + " 2 is " + numbers[2] + " 1 is " + numbers[3]); if (numbers.length == spot) { System.out.println("when spot = length. the spot is " + spot); return spot; } int value = go(numbers, spot + 1 ); System.out.println(" The value is " + value); System.out.println("spot after return " + spot); System.out.println(" the spot 2 is " + spot); return value + numbers[spot]; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload