简体   繁体   中英

Why does the recursive call print '123456' instead of '1'?

I'm having trouble understanding how the code is able to recover the remaining integers after they are taken off the original value via x/10. Is there something going on behind the scenes?

// precondition: x >= 0
// Question: What is printed from method call mystery(123456)?

public void mystery(int x) {
    if ((x/10) != 0) {
        mystery(x/10);
    }
    System.out.print(x % 10);
}

Each recursive call to mystery() happens before the final print statement that prints the digit. The current state of the program is saved to the stack before the function begins to execute again, so on the last execution of the function, when x/10 = 0, the 1 is printed. Then the program returns to the previous execution of the function, where x = 12, and continues to that print statement to print 12 % 10 = 2. This continues the same way until the program reaches the top level execution of the function.

This page explains recursion and has a useful diagram for the factorial example that shows how functions are called and returned.

Each invocation of mystery creates a new stack frame in the JVM. These frames are used to store parameters, local variables, and other data which I'll omit for brevity. In your recursive step (mystery(x / 10)), each newly created stack frame will be holding a successively smaller copy of the result of x / 10. Once the base case is reached, each stack frame will then print the value of its copy of x % 10.

So, for example, mystery(123456):

  • Frame 1: 123456
  • Frame 2: 12345
  • Frame 3: 1234
  • Frame 4: 123
  • Frame 5: 12
  • Frame 6: 1 (Base case is reached! Each frame will now print and return)

Modulo 10 will always print the rightmost digit. So that means after all the frames are finished, you will be left with 123456. If you are expecting 1, then how might you go about modifying your solution? (Hint: think about base cases!)

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