문제

I can't quite figure out what's happening inside this method when I call it with 2 as argument.

public int foo(int i) { 
    if (i > 0) { 
        System.out.println(”i: ” + foo(i - 1)); 
    } 
    return i; 
} 

This method returns two i.

1) i:0

2) i:1

I tried to understand this way. When the method is called with foo(2), the value of i is 2 and that is greater than zero. So it passes the if test. And then the method recalls itself in the print method; foo(2-1) which is foo(1). And now the value of i is 1 which again passes the if test; and in the print method foo(1-1) becomes foo(0) which does not pass the if test, so it returns the value of i which is zero now. What I don't understand here is where the second value of i which is 1 come from.

I ask for your help. Thank you.

도움이 되었습니까?

해결책

What I don't understand here is where the second value of i which is 1 come from.

Regardless of whether or not the method recurses, it always returns i. So a call of foo(2) will always return 2, even though it recurses while printing.

The output message here is confusing because it's not printing i. It may help you to understand if you change it to:

public int foo(int i) { 
    if (i > 0) { 
        int recurse = foo(i - 1);
        System.out.println("i: " + i + "; foo(i - 1): " + recurse);
    } 
    return i; 
} 

Note that you'll get the result in "reverse" order because it'll print the result of calling foo(1) while still within foo(2).

다른 팁

You have to note that the recursive call to foo() precedes the print.

Here is the execution:

//foo(2)
| calls foo(2-1)
|    //foo(1)
|    | calls foo(1-1)
|    |    //foo(0)
|    |    | prints nothing // because it does not enter the if
|    |    | returns 0      // because 0 is the argument of foo(0)
|    | prints "i: 0" // because 0 is the result of foo(0), called from foo(1)
|    | returns 1     // because 1 is the argument of foo(1)
| prints "i: 1" // because 1 is the result of foo(1), called from foo(2)
| returns 2     // because 2 is the argument of foo(2)
public int foo(int i) { 
  if(i > 0) System.out.println("i: " + foo(i - 1));
  return i; 
}

When i < 1, the loop is terminated and i is returned. However when i = 2, the code calls like this in the heap:

foo(2) { 
  System.out.println("i: " + foo(1){
    System.out.println("i: " + foo(0){
      // Condition for "if" failed here and does not continue.
      return 0; // Prints: i: 0
    });
    return 1;   // Prints: i: 1
  });
  return 2;     // Returns 2 as foo(2).
}

Interior recursive returns are used to print, but only 2 is returned at the end.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top